《读书笔记系列》==> 《C++并发实战 》

http://blog.csdn.net/column/details/ccia.html

via liuxuejiang158blog

C++并发实战:面试题2:一道迅雷笔试题
涉及c++11中的thread mutex

#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
using namespace std;
mutex m;
condition_variable cond;
int LOOP=10;
int flag=0;
void fun(int id){
for(int i=0;i<LOOP;i++){
unique_lock<mutex> lk(m);
while(id!=flag)//一定要用循环判断,若是if多个阻塞线程唤醒后同时处于临界区
cond.wait(lk);
cout<<(u_char)('A'+id)<<" ";
flag=(flag+1)%3;
cond.notify_all();
}
}
int main(){
thread B(fun,1);
thread C(fun,2);
fun(0);
cout<<endl;
B.join();
C.join();
return 0;
}

C++并发实战:面试题3:一道google笔试题
涉及c++11中的thread mutex condition_variable
iostream

#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<stdlib.h>
using namespace std;
#define LOOP 10
mutex m;
condition_variable cond;
int flag;
void fun(int num){
for(int i=0;i<LOOP;i++){
unique_lock<mutex> lk(m);
while(flag!=num)
cond.wait(lk);
cout<<num+1<<" ";
flag=(flag+1)%4;
cond.notify_all();
}
}
int main(int argc,char* argv[]){//argv[1]为0时写入A文件,2时写入B文件...
flag=atoi(argv[1]);
thread one(fun,1);
thread two(fun,2);
thread three(fun,3);
fun(0);
one.join();
two.join();
three.join();
cout<<endl;
return 0;
}

....

posted @   scott_h  阅读(4)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2018-11-04 Jlink flash 烧录HEX 程序
2015-11-04 process thread Fiber(linux)
点击右上角即可分享
微信分享提示