是否熟悉POSIX多线程编程技术?如熟悉,编写程序完成如下功能:
1)有一int型全局变量g_Flag初始值为0;
2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
3) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
4) 线程序1需要在线程2退出后才能退出
5) 主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出
这里采用C++11实现,关于std::future,std::promise实现一次性同步具体请参见我前面的一篇文章:
#include<iostream>
#include<functional>
#include<thread>
#include<future>
#include<utility>
#include<stdio.h>
#include<chrono>
#include<atomic>
#include<pthread.h>
using namespace std;
atomic<int> flag(0);//采用原子操作保护g_Flag的读写
void worker1(future<int> fut){//线程1
printf("this is thread1\n");
flag=1;
fut.get();//线程1阻塞至线程2设置共享状态
printf("thread1 exit\n");
}
void worker2(promise<int> prom){//线程2
promise<int> p=move(prom);
printf("this is thread2\n");//C++11的线程输出cout没有boost的好,还是会出现乱序,所以采用printf,有点不爽
flag=2;
p.set_value(10);//线程2设置了共享状态后,线程1才会被唤醒
printf("thread2 exit\n");
}
int main(){
promise<int> prom;
future<int> fut=prom.get_future();
thread one(worker1,move(fut));//注意future和promise不允许拷贝,但是具备move语义
thread two(worker2,move(prom));
while(flag.load()==0);
one.detach();
two.detach();
pthread_exit(NULL);//主线程到这里退出
printf("main thread exit\n");
return 0;
}
this is thread1
this is thread2
thread2 exit
thread1 exit
C++并发实战:面试题6:线程一次性同步,布布扣,bubuko.com
原文:http://blog.csdn.net/liuxuejiang158blog/article/details/22300081