Question
a few questions that you have to answer and an implementation you have to code. Write the answer in the __place indicated in this file__.
a few questions that you have to answer and an implementation you have to code. Write the answer in the __place indicated in this file__.
### Question
Describe condition variables in C++ and how they used (a few lines)
#### Answer
Write your answer here
### Implementation
Read the file __main.cpp__ in the folder **waitforothers**. We have multiple threads running the **same** code in function ``` void thread(std::string s) ```. Each thread runs through two parts: the first it prints "phase 1" and in the second it prints its name followed by 'done'. Without synchronization these two phases can be interleaved among all threads as you can see by running this program. Use condition variables and mutex to synchronize theses threads as follows: no thread can start phase two until all threads have completed phase 1. In terms of output, since we run 10 threads you must guarantee that there are 10 'phase 1' printouts before any 'done' printout. The order in which threads print 'phase one' or 'done' does not matter as long as all print 'phase 1' before **any** of them prints 'done'.
waitforothers.cpp :
#include
constexpr auto NUM_THREADS = 10;
std::default_random_engine e; std::uniform_int_distribution id(1, 1000);
void thread(std::string s) { std::cout
std::this_thread::sleep_for(std::chrono::milliseconds(id(e)));
std::cout
} int main() { std::vector<:thread> mythreads; for (int i = 0; i } ### Implementation Read the file __main.cpp__ in the folder **waitforothers**. We have multiple threads running the **same** code in function ``` void thread(std::string s) ```. Each thread runs through two parts: the first it prints "phase 1" and in the second it prints its name followed by 'done'. Without synchronization these two phases can be interleaved among all threads as you can see by running this program. Use condition variables and mutex to synchronize theses threads as follows: no thread can start phase two until all threads have completed phase 1. In terms of output, since we run 10 threads you must guarantee that there are 10 'phase 1' printouts before any 'done' printout. The order in which threads print 'phase one' or 'done' does not matter as long as all print 'phase 1' before **any** of them prints 'done'. image: answer hint
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started