I have a program that pushes 10 threads into a vector, each of which is supposed to print out a character 5 times before finishing ('A' for the first thread, 'B' for the second, etc). I'm able to get them to either run all at once (using detach()) or have them run one at a time (using join()). Now I want to use a Mutex to limit the number of threads allowed to print at a time to 2. I've been able to declare the mutex and put the lock in place but I'm unsure of how to apply a limit like this. Anyone have any ideas on how to proceed?
deque<int> q ;
mutex print_mutex ;
mutex queue_mutex ;
condition_variable queue_cond ;
void begin(int num) {
unique_lock<mutex> ul {queue_mutex};
q.emplace_back(num);
queue_cond.wait(ul,[num]{
return q.front() == num; });
q.pop_front();
cout << num << " leaves begin " << endl ;
}
void end ( int num ) {
lock_guard<mutex>lg{queue_mutex};
queue_cond.notify_all();
cout << num << " has ended " << endl ;
}
void run(int num, char ch) {
begin(num);
for (int i = 0; i < 5; ++i) {
{
lock_guard<mutex> lg { print_mutex };
cout << ch << endl << flush ;
}
sleep_for(milliseconds(250));
}
end(num);
}
int main() {
vector<thread>threads {};
for (int i = 0; i < 10; ++i) {
threads.push_back(thread{run,i,static_cast<char>(65+i)});
threads.at(i).join();
}
}