0

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?

Beny Benz
  • 13
  • 5
  • 1
    Sounds OK to me. There is no problem, (aside from lifetime issues), in one thread dereferencing a pointer to an object stored in the stack of another thread. As long as the object still exists, you can access it. – Martin James Aug 25 '20 at 02:08

1 Answers1

0

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.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • Thanks, your answer inspired me to search again, while focusing more on the implementation dependence, so e.g. pthreads will act as you described, according to this stackexchange: https://stackoverflow.com/questions/49794624/thread-access-to-stack-of-another-thread . Since I'm using an thread.h compatible header file which wraps around pthread I can be sure it will work. – Beny Benz Aug 25 '20 at 07:11
  • @Beny Benz It will work, but I'd be careful to make sure you pthread_join the child thread somewhere that the mutex is still in scope to make sure the child isn't trying access or overwrite something else in memory. – Lytigas Aug 25 '20 at 07:28
  • @Lytigas ..assuming that the thread is joined at all. It is NOT always necessary to pthread_join threads. – Martin James Aug 26 '20 at 11:45