这个程序因为把线程的创建写在了构造函数里,不用显式启动线程,也因此有些臃肿。
#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;
}