If I create thread using Pthread library under Linux, I need to use function pthread_create, as one of the arguments it takes void *, so I can pass a pointer to something, so my thread routine can get access to it, but is it safe to do something like this
{//some scope
int a=5//scope variable
pthread_create(&id,NULL,some_function,(void*)a);
}//end of scope
and in my routine:
void *some_function(void *_arg)
{
int a=(int)arg;
return NULL;
}
I want to do something like this, so I can keep the value of a variable on stack so I can access it from my thread routine but I don’t want to create struct for single variable or manually allocate memory.
I will be creating few threads like this, so I wanted to know if in situation like this I can get by and don’t use list or dynamic array.
What you’re doing is perfectly safe in the real world: conversion between
intandvoid *is not undefined behavior, it’s implementation-defined, and all implementations define it in the natural, sane way. It’s also the only efficient way to pass single-integer arguments to a new thread. Other approaches all require expensive synchronization, either via explicit locking or by usingmallocin the original thread andfreein the new thread (which has implicit synchronization cost hidden in themalloc/freeimplementation).One thing you will discover, however, is that some compilers issue warnings for the conversion. This is because of old broken code that assumes
intcan represent the full range of values ofvoid *; the compiler is unable to distinguish between the (valid) practice of storing anintin avoid *, and the (invalid) practice of storing avoid *in anint. As a solution, you might want to useintptr_tinstead ofint, which will avoid the warning. If your original variables areint, simply adding an extra intermediate cast throughintptr_twill avoid the warnings.