是否可以在不同步的情况下在不同线程上使用std :: deque :: push_back()和std :: deque :: front()/std :: deque :: pop_front()? [英] Is possible to use std::deque::push_back() and std::deque::front()/std::deque::pop_front() on different threads without synchronization?

查看:100
本文介绍了是否可以在不同步的情况下在不同线程上使用std :: deque :: push_back()和std :: deque :: front()/std :: deque :: pop_front()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生产者/消费者的情况,有一个生产者和一个消费者,共享一个共同的std :: deque.

I have a producer/consumer situation with single producer and single consumer, sharing a common std::deque.

让我写一些代码:

deque<int> dq;

void producer()
{
for (int i = 0; i < N; i++)
   dq.push_back(i);
   // signal data
}

void consumer()
{
  // get signal
  int n = dq.front();
  dq.pop_front();
}

考虑在独立线程上执行consumer()和producer().这段代码需要同步吗?

Consider consumer() and producer() being executed on independent threads. Does this code need synchronization?

推荐答案

如果您未在读取器和写入器之间进行同步,则可能会损坏数据.

If you are not synchronizing between readers and writers, there is a possibility of data corruption.

所以,答案通常是否".

So the answer in general is NO.

重新引用

多个阅读器很安全.多个线程可以同时读取 单个容器中的内容,这样就可以正常工作. 自然,容器上不得有任何作家 在读取过程中.

Multiple readers are safe. Multiple threads may simultaneously read the contents of a single container, and this will work correctly. Naturally, there must not be any writers acting on the container during the reads.

根据环境,您可以使用不同的并发容器.例如,MSDN支持并发队列,并且有 boost 库,其中提供了

Depending on the environment, you can use different concurrent containers. For example, MSDN supports concurrent queue And there are boost libraries which provides lock free containers as well.

这篇关于是否可以在不同步的情况下在不同线程上使用std :: deque :: push_back()和std :: deque :: front()/std :: deque :: pop_front()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆