c++
#include <iostream>
#include <thread>
#include <chrono>
// 共享变量 count
static int count = 100;
// 模拟卖票过程
void sell_tickets()
{
while (true)
{
if (count > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
count--;
std::cout << "Remaining count:" << count << std::endl;
}
else
{
break;
}
}
}
void task()
{
int i = 0;
while (1)
{
i++;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "守护线程" << i << std::endl;
}
}
int main()
{
// 创建两个线程,模拟两个线程同时卖票
std::thread t1(sell_tickets);
std::thread t2(sell_tickets);
std::thread t3(sell_tickets);
std::thread t4(task);
// 等待线程完成
t1.join();
t2.join();
t3.join();
//守护线程
t4.detach();
std::cout << "所有线程都结束了,程序退出!" << std::endl;
std::cout << "最终剩余票数: " << count << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
return 0;
}