简体   繁体   English

我是否需要在push_back pop_front场景中使用互斥锁锁定STL列表?

[英]Do I need to lock STL list with mutex in push_back pop_front scenario?

I have a thread push-backing to STL list and another thread pop-fronting from the list. 我有一个线程推送到STL列表和从列表弹出前面的另一个线程。 Do I need to lock the list with mutex in such case? 在这种情况下,是否需要使用互斥锁锁定列表?

From SGI's STL on Thread Safety : 来自SGI的线程安全STL

If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses. 如果多个线程访问单个容器,并且至少有一个线程可能写入,则用户负责确保在容器访问期间线程之间的互斥。

Since both your threads modify the list, I guess you have to lock it. 由于你的两个线程都修改了列表,我想你必须锁定它。

Most STL implementations are thread safe in the sens that you can access several instances of a list type from several threads without locking. 大多数STL实现都是线程安全的,您可以从几个线程访问列表类型的多个实例而无需锁定。 But you MUST lock when you are accessing the same instance of your list. 但是当你访问列表的同一个实例时,你必须锁定。

Have a look on this for more informations : thread safty in sgi stl 看看有关更多信息: sgi stl中的线程安全性

Probably. 大概。 These operations are not simple enough to be atomic, so they'll only be thread-safe if the implementation explicitly performs the necessary locking. 这些操作不够简单,不能成为原子操作,因此如果实现显式执行必要的锁定,它们将只是线程安全的。

However, the C++ standard does not specify whether these operations should be thread-safe, so it is up to the individual implementation to decide that. 但是,C ++标准没有指定这些操作是否应该是线程安全的,因此由各个实现来决定。 Check the docs. 检查文档。 (Or let us know which implementation you're using) (或者告诉我们您正在使用的实施方案)

There is no guarantee that a STL implementation is thread-safe, and since it costs performance I would guess that most aren't. 无法保证STL实现是线程安全的,并且由于它的性能成本,我猜大多数都不是。 You should definitely use a mutex. 你绝对应该使用互斥锁。

由于stl pop / push操作是AFAIK非原子操作,因此您必须使用互斥锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM