您的位置:首页 > 房产 > 建筑 > 线程和锁实践

线程和锁实践

2024/12/23 8:05:50 来源:https://blog.csdn.net/qiuzhiuser/article/details/139530728  浏览:    关键词:线程和锁实践

文章目录

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

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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com