scoped_lock 对文件不起作用?

ech*_*cho 5 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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 5

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

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

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

看起来,至少在 Windows 上,文件锁是针对每个句柄的,而不是针对每个文件的。据我所知,这意味着您的程序在 Windows 下肯定会失败。