boost::thread编程-共享互斥量

共享互斥量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;
}


你可能感兴趣的:(boost::thread编程-共享互斥量)