多线程交替打印1~10数字

  • Post author:
  • Post category:其他


#include <iostream>
#include <string.h>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <unordered_map>
#include <list>
#include <memory>
#include <functional>
#include <set>
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits.h>
#include <thread>
//#include <Windows.h>
#include <mutex>
#include <condition_variable>

using namespace std;

mutex mtx;
int number=0;
void add_1(){
    while(1){
        mtx.lock();
        if(number>10){
            mtx.unlock();
            break;
        }
        if(number%2==0){
            cout<<number<<endl;
            number++;
        }


        mtx.unlock();
    }
}

void add_2(){
    while(1){
        mtx.lock();
        if(number>=10){
            mtx.unlock();
            break;
        }
        if(number%2==1){
            cout<<number<<endl;
            number++;
        }
        mtx.unlock();
    }
}


int main(){
    thread Print_1(add_1);
    thread Print_2(add_2);
    Print_1.join();
    Print_2.join();
    return 0;
}



版权声明:本文为weixin_45794299原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。