STL队列的线程安全 [英] Thread safety for STL queue

查看:205
本文介绍了STL队列的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用队列在线程之间进行通信。我有一个读者和多个写线程。我的问题是,我需要锁定队列每次当我使用push / front / pop从队列的读者?我可以做如下:

I am using a queue to communicate between threads. I have one reader and multiple writer threads. My question is do I need to lock the queue every time when I use push/front/pop from the queue for the reader? Can I do something like the following:

//reader threads
getLock();
get the number of elements from the queue
releaseLock();

int i = 0;
while( i < numOfElements){
    queue.front();
    queue.pop();
    i++
}

这个想法是我想减少粒度锁定的代码,因为写线程只会写入队列的后面,并且只有一个读线程。只要我获得元素的数量,那么我可以从队列中获取元素,或者我需要在锁中包含front()和pop()?

The idea is that I want to reduce the granularity of the locked code and since the writer thread would only write to the back of the queue and there is only a single reader thread. As long as I get the number of elements, then I could get the elements from the queue OR do I need to enclose the front() and pop() in the lock as well?

谢谢。

推荐答案

任何未明确声明其线程安全保证的类型,互斥。也就是说,你的实现的stdlib可能允许一些变化 - 但你不能知道std :: queue的所有实现。

Any type that doesn't explicitly state its thread-safety guarantees should always be controlled by a mutex. That said, your implementation's stdlib may allow some variation of this — but you can't know for all implementations of std::queue.

由于std :: queue容器(它是一个容器适配器),你需要看看底层的容器,默认为deque。

As std::queue wraps another container (it's a container adapter), you need to look at the underlying container, which defaults to deque.

你可能会发现它更容易,更好,您自己的容器适配器,使您所需的保证。我不知道这正是为了Boost的队列。

You may find it easier, better, or more portable to write your own container adapter that makes the guarantees you need. I don't know of anything that does this exactly for a queue in Boost.

我没有看过C ++ 0x足够知道它是否有任何解决方案对于这个开箱即用的,但这可能是另一个选项。

I haven't looked at C++0x enough to know if it has any solution for this out-of-the-box, but that could be another option.

这篇关于STL队列的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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