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?
推荐答案
正如其他人已经提到的,标准容器不需要保证线程安全,因此您所要求的内容无法可移植地实现.您可以通过使用 2 个队列和一个指示写入器当前正在使用的队列的队列指针来减少读取器线程锁定写入器的时间.
As others have already mentioned, standard containers are not required to guarantee thread safety so what you're asking for cannot be implemented portably. You can reduce the time your reader thread is locking the writers out by using 2 queues and a queue pointer that indicates the queue that is currently in use by the writers.
每位作家都会:
- 获取锁
- 将元素推入队列指针当前指向的队列
- 释放锁
然后读者可以执行以下操作:
The reader can then do the following:
- 获取锁
- 切换队列指针指向第二个队列
- 释放锁
- 处理第一个队列中的元素
相关文章