简体   繁体   English

具有单独读取器和写入器线程的单个队列是否需要锁定?

[英]Does a single queue with separate reader and writer threads needs locking?

I have a shared queue (implemented using a singleton queue wrapper) and a reader thread and a writer thread. 我有一个共享队列(使用单例队列包装器实现)以及一个读取器线程和一个写入器线程。 I also have a mechanism to inform the reader thread when writer thread adds elements (enqueue) to the queue. 当写程序线程将元素(入队)添加到队列时,我还具有一种机制通知读线程。 Reader thread dequeue only one element when informed. 读取器线程在获知时仅使一个元素出队。 Is there a necessity of a Read Write Lock in this scenario. 在这种情况下是否需要读写锁。

Since writer is only enqueing and reader dequeing I feel like there is no need for a lock, if reader checks the queue size when dequeing. 由于writer仅在队列中排队,而读者在队列中排队,如果读者在队列中检查队列大小时,我觉得不需要锁定。

I assume you mean a stl::queue and no most operations on stl containers are not thread save. 我假设你的意思是一个STL ::队列和STL容器没有大多数操作都是线程保存。 For an discussion on exceptions see C++11 STL containers and thread safety . 有关异常的讨论,请参见C ++ 11 STL容器和线程安全 STL prefers speed over security (eg range check for array indices etc.) assuming that developers will implement their own checks. 假设开发人员将实施自己的检查,则STL优先考虑速度而不是安全性(例如,对数组索引进行范围检查)。

Since writer is only enqueing and reader dequeing I feel like there is no need for a lock, if reader checks the queue size when dequeing. 由于writer仅在队列中排队而读者在队列中排队如果读者在队列中检查队列大小时,我觉得不需要锁定。

Among other problems that operation alone is already unsafe, when the queue is modified by another thread. 当队列被另一个线程修改时,仅凭操作本身就已经不安全。 In c++, any unsynchronized access to a non-atomic shared variable (with at least one of them is a write) is a data race and hence UB. 在c ++中,对非原子共享变量(其中至少有一个是写操作)的任何非同步访问都是数据竞争,因此是UB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Win32的单读者单作家队列 - Single-Reader-Single-Writer Queue for Win32 多线程单读者单写入器fifo队列 - Multithreaded single-reader single-writer fifo queue 快速且无锁定的单个写入器,多个读取器 - Fast and Lock Free Single Writer, Multiple Reader 成千上万的读/写器锁在一个进程中 - Thousands of reader/writer locks in a single process 使用Writer模块的Boost中的多读取器,单写入器锁定 - Multiple-Reader, Single-Writer Lock in Boost WITH Writer Block 阻塞队列 - 可选地阻塞读取器/写入器一段时间 - Blocking Queue - optionally block the reader/writer for a certain period of time 基于单独的有状态 Reader 和 Writer 基实现 ReaderWriter 类 - Implementing a ReaderWriter class based upon separate stateful Reader and Writer bases 通过boost :: shared_mutex对g ++ - 4.4(不是C ++ 11/14)中的多个读者单一编写器实现会影响性能吗? - Does Multiple reader single writer implementation in g++-4.4(Not in C++11/14) via boost::shared_mutex impact performance? 多读者/单作者类的线程安全性 - Thread safety of multiple-reader/single-writer class std :: vector多线程同步与一个阅读器和一个编写器:仅在调整大小时锁定 - std::vector multithreaded synchronization with one reader and one writer: Only locking when resizing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM