Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scoped_lock doesn't work on file?

Tags:

boost

According to the link below, I wrote a small test case. But it doesn't work. Any idea is appreciated!

Reference: 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;
}
like image 389
echo Avatar asked Mar 24 '11 20:03

echo


2 Answers

Running the test on Linux produces your desired output. I notice these two warnings:

The page you reference has this warning: "If you are using a std::fstream/native file handle to write to the file while using file locks on that file, don't close the file before releasing all the locks of the file."

Boost::file_lock apparently uses LockFileEx on Windows. MSDN has this to say: "If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region."

It seems like, on Windows at least, the file lock is per-handle, not per-file. As near as I can tell, that means that your program is guaranteed to fail under Windows.

like image 87
Robᵩ Avatar answered Oct 20 '22 11:10

Robᵩ


Your code appears to be susceptible to this long-standing bug on the boost trac site: https://svn.boost.org/trac/boost/ticket/2796

The title of that bug is "interprocess::file_lock has incorrect behavior when win32 api is enabled".

like image 30
pestophagous Avatar answered Oct 20 '22 10:10

pestophagous