Home > Mobile >  Are these safe to do after the synchronization objects are destroyed?
Are these safe to do after the synchronization objects are destroyed?

Time:12-04

In a spare-time project of mine, I'm implementing a duplex transcoding framework. The most essential functions I'm writing are Read and Write functions, which are to be called on different threads, to exchange data like Unix Pipe/FIFO.

Because they're on different threads, I need to be sure that they're properly synchronized, and that my use of synchronization APIs are correct.

When encountering EOF, I call pthread_{condvar,mutex}_destroy functions to destroy 2 condition variables and 1 mutex. The 2 condvars are used to blocks the read and write call respectively, until input/output space are available; the mutex is the big mutex that protects the entire duplex object.

The questions are:

  1. Is it safe to signal a condition variable after it had been destroyed?

  2. Is it safe to unlock a mutex after it had been destroyed?

  3. Are there similar guarantees on other threading APIs (such as C11 Threads and C Threads)?

CodePudding user response:

  1. Is it safe to signal a condition variable after it had been destroyed?

No. Its docs say:

A destroyed condition variable object can be reinitialized using pthread_cond_init(); the results of otherwise referencing the object after it has been destroyed are undefined.


  1. Is it safe to unlock a mutex after it had been destroyed?

No. It's docs say:

A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.


  1. Are there similar guarantees on other threading APIs (such as C11 Threads and C Threads)?

About using synchronization objects after they have been destroyed? No. Why would there be? These sorts of APIs are for releasing resources. If the synchronization objects rely on resources that require cleanup in the first place, then how does it make sense that they could still function once those resources are released?

Generally speaking, then, before you can tear down synchronization objects such as mutexes and condition variables, you need to ensure that there are no circumstances under which any current thread could attempt to access them again. At least, not until after they have been re-initialized (in a framework where that is even possible). Under some circumstances it is reasonable simply not to tear them down at all. Otherwise, you need to be more creative.

CodePudding user response:

This is not safe. Destroy will destroy any shared memory used by these objects. The solution to your problem is to join all the threads that are using your your mutexes and cond-vars (except one) and only then destroy them.

  • Related