简体   繁体   English

如果只有一个线程修改 std::vector,那么同一个线程从 vector 读取时是否需要使用锁?

[英]If only one thread modifies an std::vector, does that same thread need to use a lock when it reads from the vector?

As I understand a data race can only occur with a std::vector when one or more threads are modifying a vector.据我所知,只有当一个或多个线程正在修改向量时,数据竞争才会发生在 std::vector 上。 If all threads are simply reading that is thread-safe.如果所有线程都只是简单地读取,那就是线程安全的。

Now assume I have 2 threads.现在假设我有 2 个线程。 One which can only read from the vector, but the other reads and modifies the size of the vector.一个只能从向量中读取,而另一个读取并修改向量的大小。 I have a lock to remain thread-safe to the vector.我有一个锁来保持向量的线程安全。

When the read-only thread reads from the vector it must use the lock since it does not know what the other thread is doing at the same time.当只读线程从向量中读取时,它必须使用锁,因为它不知道其他线程同时在做什么。

However, the read and write thread knows that the read-only thread is read-only and thus when it is reading the other thread can only be reading or not.但是,读写线程知道只读线程是只读的,因此当它正在读取时,另一个线程只能读取或不读取。 This means that a data-race is impossible in that case and it does not have to use the lock.这意味着在这种情况下数据竞争是不可能的,并且它不必使用锁。

The read and write thread must still use the lock when modifying the vector.读写线程在修改向量时仍必须使用锁。

Is that right?是对的吗?

You are correct.你是对的。 If your single writer thread is in read mode, then a lock does not need to happen because the other thread is only a reader.如果您的单个写入器线程处于读取模式,则不需要发生锁定,因为另一个线程只是一个读取器。 Readers can't conflict with each other.读者不能相互冲突。 The read only thread will still need to acquire the lock on every read, and the writing thread will need to lock when it writes, but it doesn't need to lock to read.只读线程在每次读取时仍然需要获取锁,而写入线程在写入时需要锁定,但不需要锁定读取。

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

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