Title: Write a program, open 3 threads, the IDs of the 3 threads are a, B, C, each thread prints its own ID on the screen 10 times, the output must be displayed in the order of ABC, such as: Abcabc .... recursion in turn.
Implemented with C++11:
[CPP]View Plaincopyprint?
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- using namespace std;
- Mutex m;
- Condition_variable cond;
- int loop=10;
- int flag=0;
- void Fun (int ID) {
- for(int i=0;i<loop;i++) {
- Unique_lock<mutex> LK (m);
- while ( id!=flag)//Must be judged by the loop, if multiple blocking threads wake up and are in the critical section
- Cond.wait (LK);
- cout<< (U_char) (' A '+id) << " " ;
- Flag= (flag+1)%3;
- Cond.notify_all ();
- }
- }
- int Main () {
- thread B (fun,1);
- thread C (fun,2);
- Fun (0);
- cout<<endl;
- B.join ();
- C.join ();
- return 0;
- }
Summary: This problem with a slightly more complex, because it has a thread, more than a thread problem comes, assuming that the cable path ABC, we want to let a first execute a part of the code, bcwait, this good to do, through the conditional variable let BC Wait, a after the BC all received the signal, this time the BC simultaneously execute? Do not handle the words are actually executed at the same time, but the question is to ensure that B first, it is important to note the red area of the code above, through while to determine: When a executes, we want to execute B, that requires a to change the flag after the mark, here is the addition of 1, when the BC received a signal continue to execute, Because while the existence, but also to judge, the result of this judgment is B jump out while, and C continue to loop stop in wait place, similarly, b after execution, the same flag, and then C jump out of the loop, so that the control 3 threads order effect. However, depending on the requirements, it is necessary to change the strategy, but the mutex, condition_variable, flag three global variables are necessary to achieve the control goal, while the other is also the essential technique to realize the control, and the other uncertain techniques are basically using while implementation.