我使用队列在线程之间进行通信.我有一个读者和多个作者线程.我的问题是,每次我从队列中为读者使用 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:
这篇关于STL 队列的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!