在 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/