Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
I have a global object which is shared by different threads. To provide the synchronization, I have added a mutex inside the global object.
Mutex will be locked by a thread before accessing the data inside the object.
Everything is fine except delete.
If a thread is locking the mutex and deleting the object.
How again it can unlock it?

How can a safe delete be implemented using this approach i.e. keeping mutex inside the object?


What I have tried:

I am not sure what can be solution.
Posted
Updated 27-Mar-17 21:37pm

1 solution

Why should a thread delete a global object?

Objects should be only deleted by the owning thread. With global objects this is probably the main thread.

Because it contains a mutex, there should be no need to delete the object. Just let it exist during the lifetime of the application.

If you want to pass dynamic data between threads, the mutex should not be part of the object holding the data.
 
Share this answer
 
Comments
Chandan_srivastava 28-Mar-17 6:54am    
I can't keep the data for the life time of the application. I have dynamic data which should be shared among threads. For synchronization, I am using mutex which is part of the data. If any thread wants to access the data, first it has to acquire the mutex.
By this way I am providing mutual exclusion. But at some point data needs to be deleted and there problem comes.
Jochen Arndt 28-Mar-17 7:12am    
But you must keep the mutex.

Just move it out of the data object (you can still have a reference to it in the object). Then you have two globals:
The mutex and a pointer to a dynamic object.

Use the mutex to control access to the object which includes creation, modification, and deletion.

Or better, create a class containing the mutex and the dynamic object that provides all the required functions. The mutex can be static (for all instances of the class) or not (one mutex for each instance).
Chandan_srivastava 28-Mar-17 10:03am    
Thanks Jochen. With this approach, I need to do management of those externally created mutexs for the data objects.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900