我正在尝试实现生产者-消费者模式。我做了功课,但仍然不能确定。实现如下:
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();
}
生产者-消费者对如下所示。可以吗,还是我也需要在这里同步?
void produce_thread()
{
while(true)
{
double data = generate_data();
m_buffer.push(data);
}
}
void consume_thread()
{
while (true)
{
double data = m_buffer.pop();
process_data(data);
}
}
void start_system()
{
boost::thread* thread_a = new boost::thread(capture_thread);
boost::thread* thread_b = new boost::thread(process_thread);
}
我怎样才能手动停止线程?可以用下面的 bool 来管理它吗?
bool enabled;
void produce_thread()
{
while(enabled)
{
// Do stuff
}
}
void consume_thread()
{
while (enabled)
{
// Do stuff
}
}