如果我们同时从 vector 追加和读取数据,是否需要锁定?(无修改)

Do we need locking if we are appending and reading data from vector simultaneously?(no-modification)

我们知道,如果多个线程对一个对象进行操作并且涉及修改,我们需要某种锁定(atomic/mutex)。对于我的情况,只有这些操作同时发生 std::vector:

1. Read
2. Append/Push

在这种情况下向量需要锁吗?如果是,为什么?我的程序是基于CPP的。

我是锁概念的新手。任何正确方向的提示都对我有用。

您很可能需要资源锁定。举个例子,如果你向向量中插入一个元素,它可能会调整大小。现在,当您调整向量大小时,如果另一个线程试图访问数组中的数据会怎样。看到冲突了吗?这就是为什么需要锁定资源。现在这是如果您插入或删除数据(意味着您更改容器的实际分配)。如果大小是固定的(意味着如果你已经预先分配了它),那么就不会有问题。

是的,您通常需要锁定,因为 push_back 会导致重新分配。

您可以查看参考资料:

https://en.cppreference.com/w/cpp/container/vector/push_back

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

https://www.cplusplus.com/reference/vector/vector/push_back/ 提及:

The container is modified. If a reallocation happens, all contained elements are modified. Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe.

所以,要小心就锁上吧。或者,如果您关心干净可维护的代码。

如果您需要额外的性能并且知道自己在做什么,只有当您知道 push_back() 不会使 size() 高于 capacity() 时,您才可以摆脱锁定。这是非常棘手且容易出错的:一旦您允许一个线程开始读取,您必须确保其他线程不会发生重新分配,甚至更晚。

编辑:重新措辞如上。 tl-dr:使用同步:-)