C++并发实战:面试题1:一道多线程笔试题
2014-03-24 18:17
405 查看
题目:子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码。
#include<iostream> #include<thread> #include<mutex> #include<condition_variable> using namespace std; mutex m; condition_variable cond; int flag=10; void fun(int num){ for(int i=0;i<50;i++){ unique_lock<mutex> lk(m);//A unique lock is an object that manages a mutex object with unique ownership in both states: locked and unlocked. while(flag!=num) cond.wait(lk);//在调用wait时会执行lk.unlock() for(int j=0;j<num;j++) cout<<j<<" "; cout<<endl; flag=(num==10)?100:10; cond.notify_one();//被阻塞的线程唤醒后lk.lock()恢复在调用wait前的状态 } } int main(){ thread child(fun,10); fun(100); child.join(); return 0; }
相关文章推荐
- C++并发实战:面试题2:一道迅雷笔试题
- C++并发实战:面试题3:一道google笔试题
- C++并发实战 与多线程
- C++并发编程实战chapter1你好,C++的并发世界--笔记0--多进程并发与多线程并发
- C++并发实战:面试题4:生产者消费者试题blocking queue
- C++并发实战:面试题6:线程一次性同步
- C++并发实战:面试题5:读者写者问题copy on write
- C++11 并发编程基础(一):并发、并行与C++多线程
- C/C++笔试面试题
- C++笔试面试题
- 秒杀多线程第一篇 多线程笔试面试题汇总
- 一道关于C++ 继承/虚函数 笔试题 [转]
- Java并发多线程面试题 Top 50
- 多线程笔试面试题汇总
- c++ 笔试面试题 难题精选 持续更新
- C++并发实战16: std::atomic原子操作
- 每天一道C++笔试题 III --- strcmp
- C++笔试题(剑指offer 面试题2 自己的string类)
- JAVA学习43_JAVA多线程和并发基础面试题
- C/C++笔试面试题