First, the preface
This example shows a simple single producer single consumer mode, one production process, another process consumption, when the buffer is full, cannot put data to the buffer, when the buffer is empty, cannot fetch data from the buffer.
Second, the Code
#include <condition_variable> #include <mutex> #include <thread> #include <iostream> #include &
lt;queue> #include <chrono> #include <unistd.h> static int i = 1; int main () {std::queue<int>products;
Product queue Std::mutex m; Std::condition_variable Cond_var; Condition variable bool Notifid = FALSE; Notice sign bool done = FALSE;
Consumer process End Flag Std::thread producter ([ampersand] () {//Capture mutex while (1) {sleep (1); Std::unique_lock<std::mutex>lock (m);
Creating a mutex guarantees that the following operations are not interrupted if (Products.size () < 3) {std::cout<< "producting" <<i<<std::endl;
Products.push (i);
Notifid = true;
++i;
Cond_var.notify_one ();
}else{//Notify another thread Notifid = true;
Cond_var.notify_one (); } if (1) done = true; Production End
Cond_var.notify_one ();
});
Std::thread consumer ([;] () {while (!done) {std::unique_lock<std::mutex>lock (M); while (!notifid) {cond_var.wait (lock); Wait for the condition variable} while (!products.empty ()) {std::cout<< "consumer" by calling the mutex number
<<products.front () <<std::endl;
Products.pop ();
} Notifid = false;
}
});
Producter.join ();
Consumer.join ();
return 0; }
Third, compiling
sudo g++-wl,--no-as-needed-std=c++11-pthread producer.cpp-o producer