(6)C++線程---thread

#include <iostream>
#include <thread>
#include <windows.h>
#include <string>
#include <mutex>
int number = 0;

std::mutex mtx;
void fun1()
{
	
	for (int i = 0; i < 1000; i++)
	{
		std::unique_lock<std::mutex> lck(mtx);
		number++;
		std::cout << number << std::endl;
	}
}
void fun2()
{
	
	for (int i = 0; i < 1000; i++)
	{
		std::unique_lock<std::mutex> lck(mtx);
		number--;
		std::cout << number << std::endl;
	}
}
int main()
{
	std::thread th1(fun1);
	std::thread th2(fun2);
	th1.join();//等待線程執行完成後再執行後續代碼
	th2.join();
	//th1.detach();
	//th2.detach(); //直接運行主線程


	system("pause");

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章