【发布时间】:2014-07-15 19:03:35
【问题描述】:
我知道std::list 不是线程安全的。在我的应用程序线程中,不断将元素添加到全局列表中。另一个线程从列表中获取元素并一个一个地处理它们。但是,我不希望处理线程在处理完成时一直锁定列表。
所以处理线程锁定列表,获取元素,解锁列表并处理元素。在处理过程中,其他线程不断向列表中添加元素。一旦处理结束,处理线程再次锁定列表删除已处理元素并解锁它。
以下是伪代码:
std::list<int> mylist ; /* Global list of integers */
void add_thread(int element) /* Threads adding element to the list */
{
write_lock();
mylist.push_back(element);
write_unlock();
return;
}
void list_processing_thread() /* Processes elements from the list */
{
for (std::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
{
read_lock();
int element = *it;
read_unlock();
process_element(element);
write_lock();
mylist.remove(element);
write_unlock();
}
return;
}
这是正确的方法(以有效的方式处理列表元素)吗?会不会有什么麻烦?
【问题讨论】:
-
你的场景是多个生产者,一个消费者,对吗?
-
@Maxim 是的,这是正确的。
标签: c++ multithreading list