我正在研究下面的函数。这个函数应该创建n个线程。它还应该打印子线程的tid。但此时我有点困惑。当我执行它并且例如我创建了5个线程,它每次都返回相同的tid。据我所知,tid是调用者的线程ID。同一个调用者调用所有这些线程吗?还是我做错了什么。 以下是代码:
void spawnThreads( unsigned int n) {
int threads = n, ret = -1;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
pid_t tid;
int i;
for(i = 0; i < threads; i++) {
ret = pthread_creation(&thread[i], NULL, (void *(*)(void *)) foo, NULL); // foo does not do anything
if( ret != 0) {
printf("pthread error!\n");
}
tid = syscall(SYS_gettid);
printf("%d %d\n", i, tid);
printf("I just created thread %d\n", i);
pthread_join(thread[i],NULL);
}
void * foo(void) {
return NULL;
}
例如,当我输入 spawnThreads(4) 时,会得到以下输出:
0 2411
I just created thread 0
1 2411
I just created thread 1
2 2411
I just created thread 2
3 2411
I just created thread 3
总之,该函数应该打印>i< >tid<。其中>tid<表示子进程的TID,>i<从1到n运行。
但是为什么我会得到四倍相同的tid?我做错了什么?如果有人能解释一下发生了什么事情,我会非常感激。
pthread_creation
。 - Erik(void *(*)(void *))
这是什么鬼? - Kninnugsyscall(SYS_gettid)
,而非你创建的新线程... - Dmitri