Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Boost条件变量用法_C++_Multithreading_Boost_Boost Thread_Condition Variable - Fatal编程技术网

C++ Boost条件变量用法

C++ Boost条件变量用法,c++,multithreading,boost,boost-thread,condition-variable,C++,Multithreading,Boost,Boost Thread,Condition Variable,我正在尝试实现生产者-消费者模式。我做了作业,但还是不能肯定。实施情况如下: boost::mutex m_mutex; boost::container::deque<T> m_buffer; boost::condition_variable fifo_loaded; T pop(void) { boost::mutex::scoped_lock lock(m_mutex); while (m_buffer.empty()) { f

我正在尝试实现生产者-消费者模式。我做了作业,但还是不能肯定。实施情况如下:

boost::mutex m_mutex;
boost::container::deque<T> m_buffer;
boost::condition_variable fifo_loaded;

T pop(void)
{
    boost::mutex::scoped_lock lock(m_mutex);

    while (m_buffer.empty())
    {  
        fifo_loaded.wait(lock); // As i understand, it releases the mutex, 
                                   and whenever it is notified, 
                                   gets it back again   
    }       
    T tmp = m_buffer.front();       
    m_buffer.pop_front();       
    return tmp; 
}


void push(const T &newElem) 
{       
    boost::mutex::scoped_lock lock(m_mutex);        
    m_buffer.push_back(newElem);        
    lock.unlock();      
    fifo_loaded.notify_one();   
}
如何手动停止线程?用下面这样的bool来管理它可以吗

bool enabled;

void produce_thread()
{
    while(enabled)
    {
        // Do stuff
    }   
}

void consume_thread()
{
    while (enabled)
    {
        // Do stuff
    }
}

您的示例实际上没有使用您编写的线程安全推送和弹出函数,而是直接调用deque的推送和弹出函数。如果它确实使用了这些,那么它将是线程安全的,生产者线程/消费者线程将不需要额外的同步

尽管如此,yohjp是正确的。你不能只让一个像“enabled”这样的不受保护的布尔值。C++11规范将数据速率定义为一个线程能够写入一个值,而另一个线程能够读取或写入该值的任何时间。此定义与C++11之前的编译器使用的定义相匹配(它只是使其成为正式定义)


enabled要么需要是原子布尔值,如boost::atomic,要么需要一个额外的互斥锁来保护“enabled”,规则是除非持有互斥锁,否则不能对其进行读写操作。

不需要更多的同步,使用
boost::atomic
而不是
bool
作为停止标志。我不明白你在第一段中说了什么,因为我的英语很差。您的意思是我的示例不使用我自己的push和pop方法,而是调用deque自己的push和pop方法吗?但我使用的是:“m_buffer.push(data);”“double data=m_buffer.pop();”
bool enabled;

void produce_thread()
{
    while(enabled)
    {
        // Do stuff
    }   
}

void consume_thread()
{
    while (enabled)
    {
        // Do stuff
    }
}