mutex, condition_variable, unique_lock et al are usually used with regards to concurrency but I don't see anything concurrent in your program at all. What is it exactly that you're trying to achieve or is this just an exercise in familiarization with these classes?
I am trying to be familiar with multithreading
also...I rarely read about mutex and this is the first time I heard about condition_variable...
so those mutex and condition_variable is important for multithreading am I right ?
a short introduction to concurrency would be in the eponymous chapter 18 in 'The C++ Standard Library (2nd edition)' by Nico Josuttis while a full-fledged book on that topic would be 'C++ Concurrency in Action – Practical Multithreading' by Anthony Williams
Coder777: while writing the reply to the following thread ... http://www.cplusplus.com/forum/beginner/218307/#msg1007225
... I recalled our conversation from a few days back and its only fair to mention that your use of plain (not atomic) bool in this case should be OK as the mutex ensures atomicity so to speak though there might be other reasons (as discussed through above link) for using std::atomic<bool>. And there should also be a check against spurious wakeups of condition variable (until C++17 comes fully into play I think) – so something on the following lines perhaps:
# include <iostream>
# include <mutex>
# include <future>
# include <condition_variable>
std::atomic<bool> done{false};
std::mutex readyMutex;
std::condition_variable cv;
void check()
{
int num{};
do
{
std::cin >> num;
} while (num != 9);
done.store(true);
}
int main()
{
auto f = std::async(std::launch::async, check);
while (!done.load())
{
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "got 9\n";
}