首页 > 编程语言 > 详细

C++并发实战:面试题6:线程一次性同步

时间:2014-03-27 18:21:47      阅读:695      评论:0      收藏:0      [点我收藏+]

是否熟悉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

C++并发实战:面试题6:线程一次性同步

原文:http://blog.csdn.net/liuxuejiang158blog/article/details/22300081

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!