c++多個線程操作與互斥


典型的c++的賣票程序,看代碼即可明白:



#include<iostream>
#include<thread>
#include<mutex>
using namespace std;


static int ticket = 100;
mutex mytmx;

void sellticket()
{
	while (ticket >= 0)
	{
		if (mytmx.try_lock())
		{
			cout << ticket << endl;
			ticket--;
			mytmx.unlock();
		}
		
	}
}
int main()
{
	

	const int group = 3;
	thread mythread[group];
	for (int i = 0; i < 3; i++)
	{

		mythread[i] = thread(sellticket);
	}
	for (int i = 0; i < 3; i++)
	{
		mythread[i].join();
	}
	
	return 0;
}



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