您为每个线程获得相同 TID 的原因是您每次都syscall(SYS_gettid)
从主线程调用,而不是从您创建的新线程中调用。您需要从线程函数内部调用它,然后提供一种方法将信息传递回主线程(如果需要)。
作为一种方法的示例(省略了一些错误检查):
创建一个结构来保存互斥体、条件、TID 和一个标志,以指示 TID 何时有效。
struct s_threadId {
pthread_mutex_t mtx; /* mutex & condition to allow main thread to
wait for the new thread to set its TID */
pthread_cond_t cond; /* '' */
pid_t id; /* to hold new thread's TID */
int ready; /* to indicate when 'id' is valid, in case
the condition wait gets interrupted */
};
然后将您的线程函数更改为锁定、设置和发出信号(并移动它,使其声明在之前 spawnThreads()
可见):
void *foo(void *arg)
{
struct s_threadId *thId = arg;
/* Lock mutex... */
pthread_mutex_lock(&thId->mtx);
/* Get and save TID and ready flag.. */
thId->id = syscall(SYS_gettid);
thId->ready = 1;
/* ..and signal main thread that we're ready */
pthread_cond_signal(&thId->cond);
/* ..then unlock when we're done. */
pthread_mutex_unlock(&thId->mtx);
/* ... */
return NULL;
}
...并修改您的spawnThreads
函数以初始化/清理结构成员并在线程设置它后获取 TID:
void spawnThreads(unsigned int n)
{
pthread_t thread; /* reused for each thread, since they run 1 at a time */
/* struct to pass back TID */
struct s_threadId threadId;
pthread_cond_init(&threadId.cond, NULL); /* init condition */
pthread_mutex_init(&threadId.mtx, NULL); /* init mutex */
int i;
for (i = 0; i < n; i++) {
/* lock mutex *before* creating the thread, to make the new thread
wait until we're ready before signaling us */
pthread_mutex_lock(&threadId.mtx);
/* clear ready flag before creating each thread */
threadId.ready = 0;
/* create threads and pass address of struct as argument */
if (pthread_create(&thread, NULL, foo, &threadId)) {
printf("pthread error!\n");
} else {
/* Wait on the condition until the ready flag is set */
while (!threadId.ready) {
pthread_cond_wait(&threadId.cond, &threadId.mtx);
}
/* Now we have the TID... */
printf("%d %d\n", i, threadId.id);
printf("I just created thread %d\n", i);
}
/* ..and unlock the mutex when done. */
pthread_mutex_unlock(&threadId.mtx);
pthread_join(thread, NULL);
}
/* When we're completely done with the struct we need to clean up the
mutex and condition variable */
pthread_mutex_destroy(&threadId.mtx);
pthread_cond_destroy(&threadId.cond);
}
在上面,需要互斥锁和条件等待来确保主线程在新线程有机会设置它之前不会尝试打印 TID。主线程启动新线程,然后等待,新线程在完成存储 TID 时发出信号,以便主线程可以继续。