c++使用条件变量实现生产消费问题(跨平台)

1. 生产者线程


思路:队列满了的情况下, 触发条件变量wait, 等待消费线程消费后唤醒继续生产.

void ProducerThreadFunc()
{
    while(1) {            
        while(/* 容器已满 */) {      
            /* 线程等待, 直到消费者消费后唤醒继续执行 */      
        }

        /* 生产动作 */   
    }   
}

2. 消费者线程


思路: 队列中没有元素可以被消费的情况下, 触发条件变量wait, 等待生产线程生产元素之后唤醒继续消费.

// 伪代码
void ConsumerThreadFunc()
{
    while(1) {            
        while(/* 容器为空 */) {          
            /* 线程等待, 直到生产者生产后唤醒继续执行 */    
        }

        /* 消费动作 */        
    }        
}

3. 完整代码


#include 

#include 
#include 
#include 
#include 
#ifdef __linux__
#include 
#else
#include 
#endif

using namespace std;

void Run_EveryWhere_Sleep(int time)
{
#ifdef __linux__
    sleep(time);
#else 
    Sleep(time * 1000);
#endif
}

class TestClass
{
public:
    int Exec()
    {
        std::thread thread_consumer(&TestClass::ConsumerThreadFunc, this);        
        std::thread thread_producer(&TestClass::ProducerThreadFunc, this);
        thread_consumer.join();
        thread_producer.join();
        return 0;
    }

    void ProducerThreadFunc()
    {
        while(1) {   
            // 使用while防止虚假唤醒         
            while(m_vecNums.size() >= 10) {      
                std::cout << "Producer Thread Wait, Current Size = " << m_vecNums.size() << endl;      
                unique_lock locker(m_mutex);
                m_cv.wait(locker);    
            }

            int num = rand();
            std::cout << "Produce One Number " << num << std::endl;            
            m_vecNums.emplace_back(num);
            m_cv.notify_all();

            Run_EveryWhere_Sleep(1);
        }   
    }

    void ConsumerThreadFunc()
    {
        while(1) {    
            // 使用while防止虚假唤醒        
            while(m_vecNums.size() <= 0) {      
                std::cout << "Consumer Thread Wait, Current Size = " << m_vecNums.size() << endl;      
                unique_lock locker(m_mutex);
                m_cv.wait(locker);    
            }

            std::cout << "Consume One Number " << m_vecNums[m_vecNums.size() - 1] << std::endl;
            m_vecNums.pop_back();
            m_cv.notify_all();

            Run_EveryWhere_Sleep(1);
        }        
    }

private:
    vector m_vecNums;          /// > 生产消费对象存储容器

    condition_variable m_cv;        /// > 条件变量
    mutex m_mutex;                  /// > 配合条件变量使用
};

int main(int argc, char **argv)
{
    TestClass A;
    return A.Exec();
}

4. 执行效果


[root@localhost condition_var_test]# g++ main.cpp -lpthread
[root@localhost condition_var_test]# ./a.out 
Produce One Number Consumer Thread Wait, Current Size = 1804289383
Produce One Number 846930886
Consume One Number 846930886
Produce One Number 1681692777
Consume One Number 1681692777
Produce One Number 1714636915
Consume One Number 1714636915
Produce One Number 1957747793
Consume One Number 1957747793
Produce One Number 424238335
Consume One Number 424238335

你可能感兴趣的:(c++技术,c++编程思想,c++,条件变量,并发,多线程,生产消费)