I have a question about pthread, when I create a variable inside a thread with malloc and then pass its pointer to a shared structure, i.e fifo, is the pointer passed by thread-1 will be accessed by thread2 ?
Please note that I have to code for the question above, I’m just trying to understand threading better, the below is just what I’m thinking about. The environment is pthread, c and linux
As far as I know threads are sharing the memory of their parent process, If that’s the case the below should be correct.
void *thread-1(void *pointer)
{
int *intp = malloc(4);
send_to_fifo(intp);
}
void *thread-2(void *pointer)
{
int *iptr;
iptr = read_from_fifo();
do_something(iptr);
free(iptr);
}
Yes: since all threads operate in a common memory space, this is allowed.
malloc,free, and other memory management functions are thread-safe by default, unless compiled withNO_THREADS.