Boost.shared_lock solves the reader and writer problem

 The class boost::shared_lock provides an inclusive lock. This class must be used with a mutex of type boost::shared_mutex. boost::shared_mutex It allows threads to acquire multiple shared ownership and one exclusive ownership, which is much more expensive than mutex. Use lock_shared() or try_lock_shared() to acquire shared ownership and unlock_shared() to release shared ownership. 

Shared_lock<shared_mutex> is used for read locks, and unique_lock<shared_mutex> is used for write locks. 

#include <boost/thread.hpp>  
#include <boost/thread/mutex.hpp>  
  
#include <iostream>  
  
  
class rw_data  
{  
private:  
    int m_x;  
    boost::shared_mutex rw_mu;  
public:  
    rw_data():m_x(0){}  
    void write()  
    {  
        boost::unique_lock<boost::shared_mutex> ul(rw_mu);  
        ++m_x;  
    }  
    void read(int *x)  
    {  
        boost::shared_lock<boost::shared_mutex> sl(rw_mu);  
        *x = m_x;  
    }  
};  
  
void writer(rw_data &d)  
{  
    for (int i = 0; i < 20; ++i)  
    {  
        boost::this_thread::sleep(boost::posix_time::seconds(10));  
        d.write();  
        cout << "writer:" << i << endl;  
    }  
}  
  
void reader(rw_data &d)  
{  
    int x;  
    for (int i = 0; i < 10; ++i)  
    {  
        boost::this_thread::sleep(boost::posix_time::seconds(5));  
        d.read(&x);  
        cout << "reader:" << x << endl;  
    }  
}  
  
void main()  
{  
    rw_data d;  
    boost::thread_group pool;  
    pool.create_thread(boost::bind(reader, boost::ref(d)));  
    pool.create_thread(boost::bind(reader, boost::ref(d)));  
    pool.create_thread(boost::bind(reader, boost::ref(d)));  
    pool.create_thread(boost::bind(reader, boost::ref(d)));  
  
    pool.create_thread(boost::bind(writer, boost::ref(d)));  
    pool.create_thread(boost::bind(writer, boost::ref(d)));  
  
    pool.join_all();  
}  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763682&siteId=291194637