c++ - 线程安全队列

标签 c++ multithreading qt mutex

在 Qt 应用程序中,我需要从一个线程添加项目,并从另一个线程使用它们。正如 Qt 文档关于容器类的说明:

... they are thread-safe in situations where they are used as read-only containers by all threads used to access them.

我假设我需要创建一个线程安全版本,或者用互斥体保护它。有什么推荐的解决方案吗?就像直接使用 Qt 事件循环,或者我缺少的任何线程安全类?

最佳答案

对于队列,是的,你需要一个线程安全的版本。我推荐 QMutex 和 QMutexLocker 一起使用,因为它会自动处理解锁。

如果您的消费者和生产者在缓冲区的不同部分工作,我推荐 semaphore相反。

Semaphores make it possible to have a higher level of concurrency than mutexes. If accesses to the buffer were guarded by a QMutex, the consumer thread couldn't access the buffer at the same time as the producer thread. Yet, there is no harm in having both threads working on different parts of the buffer at the same time.

关于c++ - 线程安全队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28352751/

相关文章:

c++ - Qt QIODevice::write/QTcpSocket::write 和写入的字节

c++ - Qt中如何在图片上显示文字?

c++ - D2D1 路径几何 : Behavior of intersecting figures

c++ - 什么时候应该在 C++ 中使用类和结构?

C++ 检查返回码

java在不同线程中访问一个对象

java - 多核处理器上当前正在运行的线程是什么?

c++ - 为什么将 'ifstream' 和 'ofstream' 添加到 "std"中,而 'fstream' 可以同时满足这两个目的?

c++ - 简单的 C++ 多线程示例未在 CentOS Linux 中编译

c++ - QApplication::processEvents 在不同的线程上