# Include
# Include
# Include
# Include
# Include
Boost: mutex;
Boost: condition_variable_any cond;
Std: vector Random_numbers;
Void fill ()
{
Std: srand (static_cast (Std: time (0 )));
For (int I = 0; I <3; ++ I)
{
Boost: unique_lock Lock (mutex );
Random_numbers.push_back (std: rand ());
Cond. policy_all ();
Cond. wait (mutex );
}
}
Void print ()
{
Std: size_t next_size = 1;
For (int I = 0; I <3; ++ I)
{
Boost: unique_lock Lock (mutex );
While (random_numbers.size ()! = Next_size)
{
Cond. wait (mutex );
}
Std: cout <random_numbers.back () <"---" <std: endl;
++ Next_size;
Cond. policy_all ();
}
}
Int main ()
{
Boost: thread t1 (fill );
Boost: thread t2 (print );
T1.join ();
T2.join ();
}
Output after compilation:
703604841 ---
397897602 ---
2011646528 ---
The program in this example is deleted.wait()Andcount(). The thread does not have to wait for one second in each loop iteration, but is executed as quickly as possible. In addition, the total amount is not calculated; the number is completely written to the standard output stream.
To ensure correct processing of random numbers, a condition variable that allows checking specific conditions between multiple threads is required to synchronize different independent threads.
As mentioned above,fill()Function is used to generate a random number for each iteration, and then placed inRandom_numbersContainer. To prevent other threads from simultaneously accessing the container, an exclusive lock is required. This example uses a conditional variable instead of waiting for one second. Callnotify_all()Will wake up each of which are being called separatelywait()The thread waiting for this notification.
Viewprint()FunctionforLoop, you can see that the same condition variable iswait()The function is called. If this thread isnotify_all()Wake up, It will try this mutex, but only infill()The function can be successfully released.
The trick here is to callwait()Releases the mutex passed in by parameters. Before callingnotify_all()After,fill()The function passeswait()Release the thread accordingly. Then it will block and wait for other threads to callnotify_all()Once the random number has been written to the standard output streamprint().
Note thatprint()Function callwait()Actually occurs in a singlewhileLoop. The purpose of this operation is to handleprint()The first call to a functionwait()The random number before the function is stored in the container. ComparisonRandom_numbersThe number and expected value of the element in, and it is found that the random number is successfully written to the standard output stream.
# Include
# Include
Using namespace std;
Void f1 (){
Cout <"f1 ()" < }
Void f2 (){
Cout <"f2 ()" < }
Int main (){
Boost: thread_group grp;
For (int I = 0; I <3; ++ I)
{
Grp. create_thread (f1 );
}
Grp. add_thread (new boost: thread (f2 ));
Cout <
Grp. join_all ();
Return 1;
}
Output after compilation:
4
F1 ()
F1 ()
F2 ()
F1 ()
This program demonstrates the usage of thread groups.