Search code examples
cmultithreadingmutexc11threads.h

Sharing mutexes stored on the main thread's stack with a child thread


While experimenting with c11 threads.h and mutexes to synchronise a network thead and a main thread I started using following procedure:

-define a mutex in the main function

mtx_t mutex_network_acqbuffer;

-initializing it with

mtx_init(&mutex_network_acqbuffer,mtx_plain);

-asigning the pointer of this mutex to a member of a heap allocated struct passed as the starting argument into my network thread

-locking the mutex in either the main thread / network thread to make sure that some data in the heap is not accessed simultaneousely.

But I'm not sure if this is the propper way to do it or if I'm just lucky that my compiler does not break my code.

I tought that the mutex resides in the stack of the main thread, so the child thread should not be able to access it, since it should be only able to acces heap allocated stuff or global variables.

But nevertheless the synchronisation seems to work.

Is there some magick trickery involved inside mtx_init which places the mutex on the heap? Or is this just implementation dependent? Should I malloc the mutex in the main thread to be on the save side/make it a global variable?


Solution

  • In C11, the fact if objects on the stack are accessible from different threads or not is implementation-defined. I personally don't know of any implementation that doesn't give access from other threads, though.