简单的一个生产者和消费者

namespace CONSUMERPRODUCT{
 
  
struct Product{
    pthread_cond_t consumer_cond;
    pthread_cond_t producer_cond;
    pthread_mutex_t thread_mutex;
    int i_product = 0;
    const int MAX_PRODUCT = 20;
    const int MIN_PRODUCT = 0;
 
  
    void init()
    {
        pthread_cond_init(&consumer_cond, nullptr);
        pthread_cond_init(&producer_cond, nullptr);
        pthread_mutex_init(&thread_mutex, nullptr);
        i_product = 0;
    }
 
  
};
 
  
class Consumer{
public:
    explicit Consumer(Product &product)
        : _product(product)
    {
 
  
    }
 
  
    void start()
    {
        std::cout << "消费线程启动..." << std::endl;
 
  
        while(1)
        {
            pthread_mutex_lock(&_product.thread_mutex);
            if (_product.i_product <= _product.MIN_PRODUCT)
            {
                pthread_cond_wait(&_product.consumer_cond, &_product.thread_mutex);
            }
            _product.i_product--;
            std::cout << "消费一个产品 剩余: [" << _product.i_product << "] 产品" << std::endl;
            pthread_cond_signal(&_product.producer_cond);
            pthread_mutex_unlock(&_product.thread_mutex);
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
    }
 
  
private:
 
  
    Product &_product;
};
 
  
class Producer{
public:
    Producer(Product &product)
        : _product(product)
    {
 
  
    }
 
  
    void start()
    {
        std::cout << "生产线程启动..." << std::endl;
        while(1)
        {
            pthread_mutex_lock(&_product.thread_mutex);
            if (_product.i_product >= _product.MAX_PRODUCT)
            {
                pthread_cond_wait(&_product.producer_cond, &_product.thread_mutex);
            }
            _product.i_product++;
            std::cout << "生产一个产品 当前: [" << _product.i_product << "] 产品" << std::endl;
            pthread_mutex_unlock(&_product.thread_mutex);
 
  
            pthread_cond_signal(&_product.consumer_cond);
 
  
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
 
  
 
  
private:
    Product &_product;
};
 
  
}
 
  
int main(int , char **)
{
    using namespace CONSUMERPRODUCT;
    Product product;
    product.init();
 
  
    Producer producer(product);
    std::thread p1(std::bind(&Producer::start, &producer));
    std::thread p2(std::bind(&Producer::start, &producer));
 
  
 
  
    Consumer consumer(product);
    std::thread c2(std::bind(&Consumer::start, &consumer));
 
  
    p1.join();
    p2.join();
    c2.join();
 
  
    return 0;
}

你可能感兴趣的:(c/c++,函数,探解)