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;
}
Basically, the GPUMon thread should print the ID of my thread which is thr->id = ka; however what I get are enormously huge numbers such as
Thread: 7793336
Thread: 7792616
I do not understand what I am doing wrong.
pthread_create()takes a reference topthread_idas its first argument.So (as a quick&dirty fix) I’d propose you change
struct thread_infoto be:Or (much nicer) do call
pthread_create()like this:The results your solution prints out are the values for the
pthread_idassigned bypthread_create()(or at least parts of it depending on your platform) which have accidently been written into the memberidofstruct thread_infoas you passed a pointer to the wrong structure.And to say it again: At least when developing do turn all compiler warnings on as (also in this case they would have) they could point you to your mistake(s) (
gccoption-Wall)