I want the program to choose a random thread each 2 seconds and make it print its number. Trying to implement it like this:Code:#include <iostream> #include <thread> #include <memory> #include <chrono> #include <condition_variable> int o = rand() % 5; std::condition_variable* cv = new std::condition_variable(); std::mutex cv_m; void threadFunc(std::shared_ptr<bool> flag2, int id) { while (true) { if (*flag2) std::cout << o; bool ifShouldPrint = (o == id); std::unique_lock<std::mutex> lock(cv_m); cv->wait(lock, ifShouldPrint(true); if (*flag2) std::cout << "Thread" << " " << id << std::endl; } } int main() { std::shared_ptr<bool> f2 = std::make_shared<bool>(false); std::thread threads[6]; for (int i = 0; i < 6; i++) threads[i] = std::thread(threadFunc, f2, i); *f2 = true; while (true) { o = rand() % 5; cv->notify_all(); std::this_thread::sleep_for(std::chrono::seconds(2)); } return 0; }
- Main cycle generates a random number and notifies all threads
- All threads compare their numbers to the generated one
- The thread the number of which is equal to the generated one unlocks and prints its number
But it gives an error in the mutex file, because of string 17 (cv->wait), because I don't really understand how to lock a thread with a condition. How do I make it work?
Thanks in advance for any help.