C++11线程——std::thread

C++11 提供头文件thread,使用std的thread实例化一个线程对象创建。

#include<iostream>
#include<thread>
#include<mutex>

using namespace std;

mutex m;
int cnt = 10;

void thread1() {
    
    
    while (cnt > 5){
    
    
        lock_guard<mutex> lockGuard(m);
        if (cnt > 0) {
    
    
            --cnt;
            cout << cnt << endl;
        }
    }
}

void thread2() {
    
    
    while (cnt > 0) {
    
    
        lock_guard<mutex> lockGuard(m);
        if (cnt > 0) {
    
    
            cnt -= 10;
            cout << cnt << endl;
        }
    }
}

int main(int argc, char* argv[]) {
    
    
    thread th1(thread1);   //实例化一个线程对象th1,该线程开始执行
    thread th2(thread2);
    th1.join();
    th2.join();
    cout << "main..." << endl;
    return 0;
}
#include<iostream>
#include<thread>
using namespace std;

void myThread(int first, int second)
{
    
    
	cout << "in my thread!  " << first << "  "<< second <<endl;
}

bool main()
{
    
    
	std::thread t1(myThread, 10, 20);//创建一个分支线程,回调到myThread函数里
	t1.join();


	cout << "in major thread" <<endl;//在主线程
	return true;
}

猜你喜欢

转载自blog.csdn.net/m0_37251750/article/details/121038940
今日推荐