/* std c++ 编写的 8 窗口出票模拟程序
* 简单就是美!
*/
#include
#include
#include
using namespace std;
int ticket_num = 1;
mutex mtx;
void run_thread(int n) //n 代表窗口号
{
while(ticket_num<=100) // 这样,ticket_num 为1--100
{
mtx.lock(); //加锁,保证只有一个线程操作ticket_num. 避免乱出票.
if(ticket_num<=100) //双重判断, 保证出到100能够停止
{
std::cout << "window "<
}
mtx.unlock(); // 解锁,让8个线程再竞争锁
}
}
int main()
{
std::thread threads[8]; // 默认构造线程
std::cout << "Spawning 8 threads...\n";
for (int i = 0; i < 8; ++i) // 创建8个线程
threads[i] = std::thread(run_thread, i + 1); // move-assign threads
for (auto &thread : threads) thread.join(); //等待各线程退出
std::cout << "All threads finished!\n";
return 0;
}