我不能让这个线程正确显示它的ID
问题描述:
struct thread_info
{
int id;
pthread_t thread_id;
int thread_num;
int gpu;
};
struct thread_info *tinfo;
static void *GPUMon(void *userdata)
{
struct thread_info *mythr = userdata;
const int thread = mythr->id;
while(1)
{
printf("Thread: %d\n", thread);
Sleep(4000);
}
return NULL;
}
int main(void)
{
struct thread_info *thr;
tinfo = calloc(2, sizeof(*thr));
for(int ka = 0; ka < 2; ka++)
{
thr = &tinfo[ka];
thr->id = ka;
if (pthread_create(thr, NULL,GPUMon, thr))
{
return 0;
}
}
// some more code
return 0;
}
基本上,GPUMon线程应该打印我的线程的ID,这是thr-> id = ka;但我得到的是非常巨大的数字,如我不能让这个线程正确显示它的ID
Thread: 7793336
Thread: 7792616
我不明白我在做什么错。
答
pthread_create()
以pthread_id
作为第一个参数。
因此(作为一个快速&脏修复),我会建议你改变struct thread_info
是:
struct thread_info
{
pthread_t thread_id;
int id;
int thread_num;
int gpu;
};
或(好得多)做电pthread_create()
这样的:
if (pthread_create(&thr->thread_id, NULL, GPUMon, thr))
{
return 0;
}
结果您输出的解决方案是由pthread_create()
(或至少部分取决于您的平台)指定的pthread_id
的值,该值已意外地写入的成员,因为你传递了一个指向错误结构的指针。
而且说了一遍:开发时至少要做到把所有的编译器警告的因为(在这种情况下,他们将有),他们可以指向你自己的错误(S)(gcc
选项-Wall
)
换句话说,OP做错了什么是用错误类型的参数调用pthread_create。显然,并没有启用所有通常的编译器警告,这肯定会引发这个问题。 –
@John Zwinck:你的名字。我的答案是否复杂? – alk
那么,我没有写出我的简单解释,因为我很钦佩你在这里写的所有内容,这是正确的和有帮助的,但是我想指出,如果他让编译器帮助他,那么OP永远不会需要帮助。 –