我是靠谱客的博主 体贴店员,最近开发中收集的这篇文章主要介绍Boost.shared_lock解决读者和写者问题,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

 boost::shared_lock 的类提供了非独占锁,这个类必须和 boost::shared_mutex 型的互斥量一起使用。boost::shared_mutex它允许线程获取多个共享所有权和一个专享所有权,它比mutex的代价高很多。通过lock_shared()或try_lock_shared()获取共享所有权,使用unlock_shared()来释放共享所有权。 

读锁定时shared_lock<shared_mutex>;

写锁定时使用unique_lock<shared_mutex> ;


实现代码如下:


#include <stdio.h>    
#include <process.h>    
#include <windows.h> 

#include<iostream>
#include<iomanip>
using namespace std;

#include <boost/thread.hpp>    
#include <boost/thread/mutex.hpp>    

typedef boost::mutex CMutex;
typedef boost::shared_mutex CSharedMutex;
typedef boost::unique_lock<boost::shared_mutex> CWriteLocker;
typedef boost::shared_lock<boost::shared_mutex> CReadLocker;
typedef boost::thread_group CThreadPool;


CMutex muConsole;//互斥访问缓冲区

class CArticle{
private:
	int iPaper;
	CSharedMutex muPaper;
public:
	CArticle(){iPaper = -1;}
	void Write(int data){CWriteLocker oWriteLocker(muPaper); iPaper = data;}
	void Read(int& data){CReadLocker oReadLocker(muPaper); data = iPaper;}
};

void WriterProc(CArticle& article, string name){
	for(int i = 0; i < 8; i++){
		boost::this_thread::sleep(boost::posix_time::seconds(1));
		article.Write(i);
		muConsole.lock();
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);    
		cout << name << " Write " << i << " Into Article." << endl;
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); 
		muConsole.unlock();
	}
}  
void ReaderProc(CArticle& article, string name){
	int data = -1;
	for(int i = 0; i < 2; i++){
		boost::this_thread::sleep(boost::posix_time::seconds(3));
		article.Read(data);
		muConsole.lock();
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);    
		cout << name << " Read " << data << " From Article." << endl;
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); 
		muConsole.unlock();
	}
}

void main()
{
	CArticle oArticle;
	CThreadPool oThreadPool;

	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); 

	oThreadPool.create_thread(boost::bind(ReaderProc, boost::ref(oArticle), "Reader1"));
	oThreadPool.create_thread(boost::bind(ReaderProc, boost::ref(oArticle), "Reader2"));


	oThreadPool.create_thread(boost::bind(WriterProc, boost::ref(oArticle), "Writer"));

	oThreadPool.create_thread(boost::bind(ReaderProc, boost::ref(oArticle), "Reader3"));
	oThreadPool.create_thread(boost::bind(ReaderProc, boost::ref(oArticle), "Reader4"));

	oThreadPool.join_all();

}

最后

以上就是体贴店员为你收集整理的Boost.shared_lock解决读者和写者问题的全部内容,希望文章能够帮你解决Boost.shared_lock解决读者和写者问题所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(31)

评论列表共有 0 条评论

立即
投稿
返回
顶部