zoukankan      html  css  js  c++  java
  • 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
    ";
            //cout << "t111111" << endl;
            cout << cnt << endl;
        }
    }
    
    void t2()//普通函数,用来执行线程
    {
        lock_guard<mutex> lock(m);
        while(cnt>0)
        {
            --cnt;
            //cout << "t2222222
    ";
            //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 
    
    ";
        //cout << "Here is main" << endl;
        return 0;
    }

    2.详细解析参考链接

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

  • 相关阅读:
    适配器模式
    事务
    JUnit4
    命令模式
    组合模式
    MySQL语法
    MyEclipse工具
    数据源和连接池
    Annotation
    Java反射机制
  • 原文地址:https://www.cnblogs.com/paulprayer/p/10366806.html
Copyright © 2011-2022 走看看