The condition_variable of c++11 multithreaded programming
Mainly from a problem, write a program to open 3 threads, the IDs of these 3 threads are a, B, C, each of which prints their IDs 10 times on the screen, requiring the output to be displayed in the order of ABC; for example: Abcabc. Here you can use C++11 conditional variables to solve the problem. The knowledge points involved include:
1.std::unique_lock
First we introduce Unique_lock, which is an exclusive lock, and its constructors have several scenarios:
Unique_lock ();(1) (since c++11)
Unique_lock (unique_lock&& Other);(2) (since c++11)
Explicit Unique_lock (mutex_type& m);(3) (since c++11)
Unique_lock (mutex_type& m, std::d efer_lock_t t);(4) (since c++11)
Unique_lock (mutex_type& m, std::try_to_lock_t t);(5) (since c++11)
Unique_lock (mutex_type& m, std::adopt_lock_t t);(6) (since c++11)
template< class Rep, Class Period >unique_lock (mutex_type& m,conststd::chrono::d uration<rep,period> & Timeout_duration);(7) (since c++11)
template< class Clock, Class Duration >unique_lock (mutex_type& m,const, duration>& timeout_time);(8) (since c++11)
One of the more special is 4,5,6, respectively, that does not own a mutex, trying to own the lock, the other people's lock adoption.
7,8 is a time-related lock.
2.std::condition_variable
The second is this thing, which must first hold a Unique_lock variable.
3 Code implementation
#include <iostream>
#include <thread>
#include <condition_variable>
#include < mutex>
int g_index = 0;
const int g_threads = 5;
std::condition_variable CV;
Std::mutex MX;
void func (int i);
int main ()
{
std::thread th[g_threads];
for (int i = 0; i < g_threads i++)
{
Th[i] = Std::thread (func, I);
}
for (int i = 0; i < g_threads i++)
th[i].join ();
return 0;
}
void func (int gi)
{for
(int i = 0; i < i++)
{
std::unique_lock<std::mutex> lk (MX);
cv.wait (lk, [=] () {return GI = g_index;});
Std::cout << (char) (' A ' + gi);
if (G_index = = g_threads-1)
std::cout << Std::endl;
g_index++;
G_index%= g_threads;
Lk.unlock ();
Cv.notify_all ();
}
4 output
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE