共享互斥量shared_mutex允許線程獲取多個共享所有權shared_lock和一個專享所有權uique_lock,實現了讀寫鎖機制,即多個讀線程一個寫線程。
~~~
#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>
boost::mutex io_mu;//io讀寫鎖
class rw_data
{
public:
rw_data():m_x(0){}//構造函數
void write()//寫數據
{
boost::unique_lock<boost::shared_mutex> ul(rw_mu);//寫鎖定,使用unique_lock<shared_mutex>
++m_x;
}
void read(int *x)//讀數據
{
boost::shared_lock<boost::shared_mutex> sl(rw_mu);//讀鎖定,使用shared_lock<shared_mutex>
*x=m_x;
}
private:
int m_x;//用于讀寫的數據變量
boost::shared_mutex rw_mu;//共享互斥量
};
//定義用于線程執行的多次讀寫函數
void writer(rw_data &d)
{
for(int i=0;i<10;++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(10));//休眠
d.write();
}
}
void reader(rw_data &d)
{
int x=0;
for(int i=0;i<10;++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(5));//休眠
d.read(&x);
boost::mutex::scoped_lock lock(io_mu);//鎖定IO
std::cout<<"reader:"<<x<<std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
rw_data d;
boost::thread_group tg;
tg.create_thread(boost::bind(reader,boost::ref(d)));
tg.create_thread(boost::bind(reader,boost::ref(d)));
tg.create_thread(boost::bind(reader,boost::ref(d)));
tg.create_thread(boost::bind(reader,boost::ref(d)));
tg.create_thread(boost::bind(writer,boost::ref(d)));
tg.create_thread(boost::bind(writer,boost::ref(d)));
tg.create_thread(boost::bind(writer,boost::ref(d)));
tg.create_thread(boost::bind(writer,boost::ref(d)));
tg.join_all();
getchar();
return 0;
}
~~~