我今天在 C 编程书的进程和线程章节中遇到了这行代码:
printf("[Child] child thread id: 0x%x\n", (unsigned int)pthread_self());
我从未见过这部分(unsigned int)pthread_self()
,我不知道第一对括号是做什么用的。任何的想法?
ps:
我记得在php的文档中,函数文档有类似的表达:
int time()
但在实际代码中,我们只使用了 part time()
, int 是为了说明函数的返回值time()
更新:
我在书中输入了测试每个线程 id 的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
int global = 5;
void* ChildCode(void* arg) {
int local = 10;
global++;
local++;
printf("[Child] child thread id: 0x%x\n", (unsigned int)pthread_self());
printf("[Child] global: %d local: %d\n", global, local);
pthread_exit(NULL);
}
int main() {
pthread_t childPid;
int local = 10;
printf("[At start] global: %d local: %d\n", global, local);
/* create a child thread */
if (pthread_create (&childPid, NULL, ChildCode, NULL) != 0)
{
perror("create");
exit(1);
} else { /* parent code */
global++;
local--;
printf("[Parent] parent main thread id : 0x%x\n", (unsigned int)pthread_self());
printf("[Parent] global: %d local: %d\n", global, local);
sleep(1);
}
printf("[At end] global: %d local: %d\n", global, local);
exit(0);
}
它给了我一些注意事项(不是警告不是错误):
clang example_thread.c
/tmp/example_thread-9lEP70.o: In function `main':
example_thread.c:(.text+0xcc): undefined reference to `pthread_create'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我不知道代码,知道吗?