1.并发访问
2.互斥量处理同步
3.lock_guard
4.unique_guard
5.async
6.async异步操作
7.async同步操作
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
#include <queue>
#include <list>
#include <future>
using namespace std;
mutex mutex1;
void func(){
int count = 3;
while (count >0){
mutex1.lock();
cout <<"thread_"<< this_thread::get_id()<< "...count ="<< count << endl;
count--;
mutex1.unlock();
usleep(1000*500);
}
}
class Box{};
mutex mutex2;
queue <Box *> qu;
void init(){
for (int i = 0; i < 10; ++i) {
qu.push(new Box());
}
}
bool flag = true;
void moveOut(string name){
mutex2.lock();
if(!qu.empty()){
usleep(1000*300);
qu.pop();
cout<< name << "搬走一个,剩余="<<qu.size()<<endl;
}else{
flag = false;
}
mutex2.unlock();
}
void func1(){
while (flag){
moveOut("func1");
usleep(1000*100);
}
}
void func2(){
while (flag){
moveOut("func2");
usleep(1000*60);
}
}
mutex mutex3;
void work(){
int n = 10;
while (n >0){
lock_guard<mutex> lg(mutex3);
cout << this_thread::get_id() << "n="<< n <<endl;
n--;
usleep(1000*100);
}
}
mutex mutex4;
void work2(){
int na = 10;
while (na>0){
unique_lock<mutex> u1(mutex4);
cout << this_thread::get_id()<<"na="<<na <<endl;
na--;
u1.unlock();
usleep(1000*100);
}
}
int add(int a,int b){
return a+b;
}
int main() {
thread t1(func);
thread t2(func);
t1.join();
t2.join();
init();
thread t3(func1);
thread t4(func2);
t3.join();
t4.join();
thread t5(work);
thread t6(work);
t5.join();
t6.join();
thread t7(work2);
thread t8(work2);
t7.join();
t8.join();
future<int> f = async(add,1,2);
int result = f.get();
cout << "result ="<< result <<endl;
async(launch::async,add,1,3);
future<int> f2 = async(launch::deferred,add,10,20);
f2.get();
return 0;
}