Reputation: 1899
I have several processes but only one should be running at the time. This means that let's say the Process1 is running and if the Process2 get launched, then Process2 should wait until Process1 is complete. I am considering the boost named_mutex for this with code like below.
#include <iostream>
#include <boost/interprocess/sync/named_mutex.hpp>
using namespace boost::interprocess;
int main()
{
named_mutex mutex(open_or_create, "some_name");
try
{
mutex.lock();
// Do work
mutex.unlock();
}
catch (const std::exception& ex)
{
mutex.unlock();
std::cout << ex.what();
}
}
Questions:
1. I would like to make sure that there is no situation where Process2 get starved of acquiring the lock if Process1 encounters any handled/unhandled exception?
2. Is there any c# like finally mechanism in c++ that could be helpful in this use-case?
Upvotes: 0
Views: 50
Reputation: 275385
Finally in C# is a procedural emulation of RAII. As automatic storage variables have deterministic lifetime in C++ (scope wise), just do the unlock in a destructor.
The std
library type is unique_lock
; boost will have a similar one. Have that lock the mutex, and unlock on destruction.
Upvotes: 1