首页 > 编程语言 > 详细

01. C++ 多线程入门实例

时间:2019-02-12 19:48:01      阅读:141      评论:0      收藏:0      [点我收藏+]

1.可复用的完整实例

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

//全局变量,有待改进!
int cnt = 20;
mutex m;

void t1()//普通函数,用来执行线程
{
    lock_guard<mutex> lock(m);
    while(cnt>0)
    {
        --cnt;
        //cout << "t1111111\n";
        //cout << "t111111" << endl;
        cout << cnt << endl;
    }
}

void t2()//普通函数,用来执行线程
{
    lock_guard<mutex> lock(m);
    while(cnt>0)
    {
        --cnt;
        //cout << "t2222222\n";
        //cout << "t2222222" << endl;
        cout << cnt << endl;
    }
}

int main() {
    thread th1(t1);//实例化一个线程对象th1,使用函数t1构造,然后该线程就开始执行了
    thread th2(t2);

    th1.join();//等待th1执行完
    th2.join();//等待th2执行完

    cout << "Here is main \n\n";
    //cout << "Here is main" << endl;
    return 0;
}

 

2.详细解析参考链接

http://www.cnblogs.com/whlook/p/6573659.html C++:线程(std::thread) 

01. C++ 多线程入门实例

原文:https://www.cnblogs.com/paulprayer/p/10366806.html

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