2

Is it possible to allocate and init a mutex in one thread and destory it in another?

Thanks.

1 Answers1

4

Yes. Mutexes are process resources that are shared between threads. Just make sure there's no way another thread could be accessing the mutex at the time it's destroyed or after.

It is a very common pattern to construct an object with a mutex and then later destroy that mutex when the object is destroyed. It would be very irritating if you had to make sure the same thread destroyed the mutex as created it -- that thread might not even exist any more. If it's a process shared mutex, the process that create it might not even exist any more.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Thanks David. If i want the mutex to be per object, can it be part of the class? And if so, should i define it as a regular data memeber? For example- pthread_mutex_t m_spinlock; – user1035931 Mar 21 '13 at 10:49
  • Yes, you can do that. Just don't try to use that very mutex to protect the destruction of the class. Typically, such an object would live in a collection that is itself protected by a mutex. Adding an object to the collection or removing it from the collection for destruction would be done under the protection of that outer mutex. You can also use smart pointers. – David Schwartz Mar 21 '13 at 11:04