Question: a question that you have to answer and an implementation you have to code. Write the answer in the __place indicated in this file__. ###

a question 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 #include #include #include #include #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

}

a question that you have to answer and an implementation you haveimage: answer hint

Answer Condition variable A condition variable is an object able to block the calling thread until notified to resume. It uses a unique_lock (over a mutex) to lock the thread when one of its wait functions is called. The thread remains blocked until woken up by another thread that calls a notification function on the same condition_variable object. Objects of type condition_variable always use unique lock to wait

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!