提升进程间file_lock理解/使用

时间:2018-04-02 16:08:19

标签: boost boost-interprocess

我在boost::interprocess::interprocess_mutex实例中使用匿名互斥(boost::interprocess::managed_shared_memory)时遇到了问题。即,如果软件崩溃,则会出现问题;互斥锁可能会保持锁定状态(取决于崩溃时的状态)。它也可以使调试变得有趣:)。

我的理解是我可以用boost::interprocess::file_lock(FL)替换interprocess_mutex。 @DaveF发布了我想要构建的some questions。在我使用FL之前,我希望能够很好地了解自己所处的内容。

  • 我可以在FL中使用匿名boost::interprocess::condition_variable(CV)吗?查看完代码后,它似乎可以正常工作。
  • 在使用简历时,我是否打开了自己在使用互斥锁时遇到的相同问题(即,如果应用程序在没有正确清理/完成的情况下意外结束)?
  • 创建FL的最佳方法是什么?我已经想过类似以下的东西......

注意代码可能无法编译:

namespace bi = boost::interprocess;
namespace bf = boost::filesystem;

const std::string strSharedMemName = std::string("cp_shdmem_") + std::to_string(nIdx);
const std::string strNamedMutexName = strSharedMemName + "_mtx";

// I'm working on Linux, but would like to Boost to create a temporary file path.
const bf::path pathTmpFile =
    bf::temp_directory_path() / (strNamedMutexName + ".txt");

{
    // 1. So can I just create the file? What happens if it exists? Boost docs say this
    // about the file_lock constructor:
    //   "Throws interprocess_exception if the file does not exist 
    //    or there are no operating system resources."
    // 2. What happens if file already exists?
    bf::ofstream f(pathTmpFile);
}

// Create.
bi::file_lock lockFile(pathTmpFile.string().c_str());

// Lock.
bi::scoped_lock<bi::file_lock> lockNamed(lockFile);

平台细节:

  • Ubuntu 17.10
  • Boost 1.63
  • GCC 7.2

0 个答案:

没有答案
相关问题