我正在做一个处理多线程运动的应用程序。假设我们有 10 辆汽车,并且有一个最多可容纳 5 辆汽车的停车场。如果一辆汽车不能停车,它会等到有空闲空间。
我正在使用 c++11 线程执行此操作:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
int cars=0;
int max_cars=5;
mutex cars_mux;
condition_variable cars_cond;
bool pred()
{
return cars< max_cars;
}
void task()
{
unique_lock<mutex> lock(cars_mux);
while(true)
{
cars_mux.lock();
cars_cond.wait(lock,pred);
cars++;
cout << this_thread::get_id() << " has parked" << endl;
cars_mux.unlock();
this_thread::sleep_for(chrono::seconds(1)); // the cars is parked and waits some time before going away
cars_mux.lock();
cars--;
cars_cond.notify_one();
cars_mux.unlock();
}
}
int main(int argc, char** argv)
{
thread t[10];
for(int i=0; i<10; i++)
t[i]=thread(task);
for(int i=0; i<10; i++)
t[i].join();
return 0;
}
问题是没有输出,似乎所有线程都被阻塞等待。