线程和锁实践

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;


/*
 * 1.并发访问
 * 2.互斥量处理同步
 * 3.lock_guard
 * 4.unique_guard
 * 5.async
 * 6.async异步操作
 * 7.async同步操作
 * */

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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值