多线程互斥 基于c++11

来源:互联网 发布:java布局思想 编辑:程序博客网 时间:2024/05/24 06:45
#include <thread>#include <iostream>#include <mutex>std::mutex m;int count=10;bool debug=true;//控制 是否使用互斥using std::cout;using std::endl;void hello1(){    if(debug)        m.lock();    for(int i=0;i<1000;i++)    {        count++;        cout<<"1"<<std::flush;    }    if(debug)        m.unlock();}void hello2(){    if(debug)        m.lock();    for(int i=0;i<1000;i++)    {        count--;        cout<<"2"<<std::flush;    }    if(debug)        m.unlock();}int main(){    std::thread t1(hello1),t2(hello2);    t1.join();    t2.join();    std::cout<<"Main Thread "<<count<<std::endl;    return 0;}


0 0
原创粉丝点击