C + + simple single producer single consumer mode __c++

Source: Internet
Author: User
Tags mutex

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




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.