01 C++ 多线程入门实例


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)

优质内容筛选与推荐>>
1、Ansible
2、用PARSENAME函数拆分字符串
3、面向对象五大原则_1.单一职责原则&2.里氏替换原则
4、SQL Server 中易混淆的数据类型
5、关于C#中用access做数据库,使用like语句的问题


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号