7

I'm using boost::interprocess::scoped_lock, if the application crash for some reason inside the scope the mutex isn't released. Next time the application is executed (without restarting the computer), the mutex is locked.

How's this intended to work? I give a simple example of the code below.

{
    boost::interprocess::named_mutex lockMutex(boost::interprocess::open_or_create, "lockName");
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(lockMutex);
    //crash here
}

I ended up doing a timeout like below. Anyone who could come up with a solution that doesn't limit the time for lock?

boost::interprocess::named_mutex named_mtx(boost::interprocess::open_or_create, lockName.c_str());

    while(true)
    {
        if(named_mtx.try_lock())
        {
            break;
        }

        if(!named_mtx.timed_lock(boost::get_system_time() + boost::posix_time::milliseconds(TIMEOUT_MILLISECONDS)))
        {
            named_mtx.unlock();
        }
    }
Tim Post
  • 33,371
  • 15
  • 110
  • 174
thenail
  • 438
  • 1
  • 5
  • 10

1 Answers1

3

That's seems perfectly logic to me :)

As your application crash, the mutex which maps to your OS interprocess communication mechanism (IPC) is not released. When your application restart it tries to get the mutex without success !

I suppose your application has different subsystems (processes) that need to be synchronized.

You have to devise a global policy in case of a crash of one of your subsystem to manage correctly the lock. For example, if one of your subsystem crash, it should try and unlock the mutex at startup. It can be tricky as other subsystems use that lock. Timeouts can help too. In any case, you have to devise the policy having in mind that any of your processes can crash while having locked the mutex...

Of course, if you do not need interprocess locking, use simple scoped locks :)

my2c

neuro
  • 14,948
  • 3
  • 36
  • 59
  • Boost uses files for emulation of named mutexes. If app crashes - file remain in file system... OS mutexes does not used. Check sources... – Victor Mezrin Mar 03 '16 at 10:46
  • @Victor: Whatever OS mechanism used, the problem, as I answered, is that there's no policy to manage problems. No need to see library code to tell that. Boost using file to implement named mutexes is not the problem, the problem is the management of shared resource ... – neuro Mar 07 '16 at 09:48