Search code examples
c++boostmutexboost-thread

C++: Mutex and deallocation


I am writing a small program as part of a University course. In this program, I have a global Boost Mutex which helps me to coordinate two threads.

In my small library, I have to write a cleanup function that, when invoked, literally cleans up after itself.

What I am asking now is: if I create a Mutex, am I supposed to deallocate it as well when I do not need it anymore?

The code I use is simply

boost::mutex mymutex;

Thanks a lot


Solution

  • Boost mutexes appear to be written to perform all their cleanup in their destructors. If you want to ready that same mutex for resuse, probably you'd want to call .unlock() on it once.

    If you really feel the need to manually get rid of it, I suppose you could make it a pointer and create it with a new. That way you can manually control running of its destructor in your cleanup routine by calling delete on the pointer. However, pointers are kind of error-prone, so using one just so you can show it manually being cleaned up (instead of having it automatically happen when the object goes out of scope at the end of your program) is stoopid. If you get docked a couple of points for not doing that, I'd consider it a small price to pay for designing things right instead.

    If you are really worried about losing points for not manually cleaning up your automatically destructed resources, if I were you I'd go ask my instructor what I need to do. School ain't free (unlike SO), and such consulting is part of what you are paying them all that money for. Might as well get some value for it.