I am doing an application which handle multithreading for exercise.Let's suppose that we have 10 cars, and there is a parking which may contain at maximum 5 cars.If a car can't park it waits until there is a free room.
I am doing this with c++11 threads:
#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;
}
The problem is that there is no output, it seems like all threads are blocked waiting.