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) 

猜你喜欢

转载自www.cnblogs.com/paulprayer/p/10366806.html