Pages

Named mutex

A named mutex could be used in IPC context to synchronize processes on a file. The code showed in the example puts on a file a string that include the thread id of the current process and a counter. If we execute it in different processes, the strings could be mixed up, so we use a lock on the named mutex to let any process having exclusive access to the file when writing.

Here is the code:
#include <fstream>
#include <iostream>
#include <string>

#include "boost/interprocess/sync/scoped_lock.hpp"
#include "boost/interprocess/sync/named_mutex.hpp"
#include "boost/thread/thread.hpp"

using namespace boost::interprocess;

namespace
{
class FileManager // 1.
{
private:
named_mutex mutex_;
std::ofstream file_;

public:
FileManager() : mutex_(open_or_create, "fstream_named_mutex"),
file_("boost.log", std::ios_base::app) {}
~FileManager() { named_mutex::remove("fstream_named_mutex"); }

void log(std::string line)
{
scoped_lock<named_mutex> lock(mutex_);
file_ << line << std::endl;
}
};
}

void ip08()
{
try
{
FileManager fm;

for(int i = 0; i < 10; ++i)
{
std::cout << '.'; // a sign of life for the user ...
std::ostringstream os("Process id ");
os << boost::this_thread::get_id() << " iteration # " << i;

fm.log(os.str());
boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); // 2.
}
std::cout << std::endl;
}
catch(interprocess_exception &ex)
{
std::cout << ex.what() << std::endl;
return;
}
return;
}

1. through the class FileManager we manage the file stream and the associated mutex, the constructor open the file, in append mode, and create or open the named mutex we use to rule the access to the file. The destructor removes the mutex. The log() methods use a scoped lock on the mutex to safely perform the write to the file.
2. a sleep is used to let the user interact to the execution.

The code is based on an example provided by the Boost Library Documentation.

No comments:

Post a Comment