scoped_lock在文件上不起作用?

时间:2011-03-24 20:24:31

标签: boost

根据下面的链接,我写了一个小测试用例。但它不起作用。任何想法都表示赞赏!

参考: http://www.cppprog.com/boost_doc/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.file_lock.file_lock_careful_iostream

#include <iostream>
#include <fstream>

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

using namespace std; 
using namespace boost::interprocess;

int main()
{
    ofstream file_out("fileLock.txt");
    file_lock f_lock("fileLock.txt");

    {
        scoped_lock<file_lock> e_lock(f_lock);  // it works if I comment this out
        file_out << 10;
        file_out.flush();
        file_out.close();
    }

    return 0;
}

3 个答案:

答案 0 :(得分:4)

在Linux上运行测试会产生所需的输出。我注意到这两个警告:

您引用的页面有此警告:“如果您使用std :: fstream / native文件句柄在该文件上使用文件锁时写入该文件,请不要在释放所有锁之前关闭该文件文件。”

Boost::file_lock显然在Windows上使用LockFileExMSDN有这样的说法:“如果锁定过程再次打开文件,它将无法通过此第二个句柄访问指定区域,直到它解锁该区域。”

似乎至少在Windows上,文件锁是每个句柄,而不是每个文件。尽管我可以说,这意味着您的程序可以保证在Windows下失败。

答案 1 :(得分:3)

您的代码似乎容易受到此追踪网站上长期存在的错误的影响:https://svn.boost.org/trac/boost/ticket/2796

该错误的标题是“ interprocess :: file_lock在启用win32 api时行为不正确”。

答案 2 :(得分:0)

这是一种解决方法,可以附加到基于Boost 1.44的文件锁定文件中。

#include "boost/format.hpp"
#include "boost/interprocess/detail/os_file_functions.hpp"

namespace ip = boost::interprocess;
namespace ipc = boost::interprocess::detail;

void fileLocking_withHandle()
{
  static const string filename = "fileLocking_withHandle.txt";  

  // Get file handle
  boost::interprocess::file_handle_t pFile = ipc::create_or_open_file(filename.c_str(), ip::read_write);
  if ((pFile == 0 || pFile == ipc::invalid_file()))
  {
    throw runtime_error(boost::str(boost::format("File Writer fail to open output file: %1%") % filename).c_str());
  }

  // Lock file
  ipc::acquire_file_lock(pFile);

  // Move writing pointer to the end of the file
  ipc::set_file_pointer(pFile, 0, ip::file_end);

  // Write in file
  ipc::write_file(pFile, (const void*)("bla"), 3);

  // Unlock file
  ipc::release_file_lock(pFile);

  // Close file
  ipc::close_file(pFile);
}