C++:多线程互斥访问资源的Demo

这个程序因为把线程的创建写在了构造函数里,不用显式启动线程,也因此有些臃肿。

#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
#include <math.h>
#include <unistd.h>
using namespace std;

//rand()%(b-a+1)+a;

mutex mx;

class A{
  public:
	//A(){
	//}
	void run(int * data){
		srand((unsigned)time(NULL));
		int n;
		while(true){
			n=rand()%9+1;
			{
				unique_lock<mutex> lock(mx);
				for(int i=0;i<20;i++){
					data[i]=i+1+n*100;
				}
			}
		}
	}
};

class B{
  public:
	//B(){
	//}
	void run(int * data){
		while(true){
			{
				unique_lock<mutex> lock(mx);
				for(int i=0;i<20;i++)
					cout<<data[i]<<" ";
			}
			cout<<endl;
			sleep(1);
		}
	}
};

class System{
  public:
	System(){
		a=new A();
		b=new B();
		thA=new thread(&A::run,a,data);
		thB=new thread(&B::run,b,data);
	}
	void run(){
		cout<<"Do nothing."<<endl;
	}
  private:
	int data[20];
	A * a;
	B * b;
	thread * thA;
	thread * thB;
};

int main(){
	System sys;
	getchar();
	//sys.run();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值