C++ boost::thread::mutex::unique_lock()














































C++ boost::thread::mutex::unique_lock()



Description:
Unique lock
unique lock is an object that manages a mutex object with unique ownership in both states: locked and unlocked.

Unique_lock is similar to lock_guard() but provide more flexibility.With unique_lock se can even construct the locker without actually locking the mutex .To do that we need to pass over another parameter of defer_lock() .

On construction (or by move-assigning to it), the object acquires a mutex object, for whose locking and unlocking operations becomes responsible.

The object supports both states: locked and unlocked.

This class guarantees an unlocked status on destruction (even if not called explicitly). Therefore it is especially useful as an object with automatic duration, as it guarantees the mutex object is properly unlocked in case an exception is thrown.

Note though, that the unique_lock object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the unique_lock that manages it.

Locking/unlocking


HEADER:
<boost/thread.hpp>
<fstream>
<string>
<iostream>

SOURCE CODE:

#include <boost/thread.hpp> #include <iostream> #include <fstream> #include <string> using namespace std; class logfile { boost::mutex mu; std::ofstream f; public: logfile () //constructor { f.open("log.txt"); } void shared_print(std::string id,int value) { boost::unique_lock<boost::mutex>locker(mu,boost::defer_lock); //it uses RAII cout<<"*"; locker.lock(); f<<" "<<id<<":"<<value<<endl; locker.unlock(); boost::unique_lock<boost::mutex>locker2 =boost::move(locker); } }; void function_1(logfile & log) { for(int i=0;i>-5;i--) log.shared_print("from t1",i); } int main() { logfile log; // pass the log to thread t1 by the reference. boost::thread t1(function_1,boost::ref(log)); for(int i=0;i<5;i++) log.shared_print("from main:",i); t1.join(); return 0; }




Comments