boost::interprocess::scoped_lock 应用程序在锁内崩溃
我正在使用 boost::interprocess::scoped_lock,如果应用程序由于某种原因在作用域内崩溃,互斥体不会被释放。 下次执行应用程序时(无需重新启动计算机),互斥体将被锁定。
这是如何运作的? 我给出了下面代码的简单示例。
{
boost::interprocess::named_mutex lockMutex(boost::interprocess::open_or_create, "lockName");
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(lockMutex);
//crash here
}
我最终做了如下所示的超时。谁能想出一个不限制锁定时间的解决方案?
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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对我来说似乎完全符合逻辑:)
当您的应用程序崩溃时,映射到操作系统进程间通信机制(IPC)的互斥锁不会被释放。当您的应用程序重新启动时,它尝试获取互斥体但没有成功!
我想您的应用程序有不同的子系统(进程)需要同步。
您必须制定一项全局策略,以防某个子系统崩溃,以便正确管理锁。例如,如果您的子系统之一崩溃,它应该尝试在启动时解锁互斥体。当其他子系统使用该锁时,这可能会很棘手。超时也有帮助。无论如何,您必须设计策略,记住锁定互斥体时任何进程都可能崩溃...
当然,如果您不需要进程间锁定,请使用简单的作用域锁:)
my2c
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