Closed redboltz closed 3 years ago
There's two ways to answer this:
modify
is not const, your scenario is not safe.modify
does not actually modify anything (other than the element itself). So, yes, the scenario is unofficially safe. In this case, though, I think it's more informative and clear to just const_cast
the element and avoid using modify
.Thank you for prompt response.
As you mentioned, const_cast
is the best choice for this situation.
So I will update as follows:
mf.modify(
it,
[](auto& e) {
++e.no_key;
}
);
++const_cast<std::atomic<int>&>(it->no_key);
Here are a class and a multi_index contaier.
key1 and key2 are used as index key but no_key doesn't. In order to access the container, I use
boost::shared_mutex
.When I insert to mf or erase from mf, I use exclusive lock.
When I want to update no_key, I can't do as follows:
It's because it is const_iterator. It is reasonable that if key1 or key2 is overwritten, indexes would be broken.
So I need to do as follows:
After mod lambda expression is called, multi_index container can re-calculate indexes.
modify() is called is shared lock guard. That means multiple threads can call modify() concurrently. Is it safe as long as I update only no key members in modify() function from multiple threads ? NOTE no_key itself is thread safe because
std::atomic<int> no_key
.I'm not sure after mod function called process is thread safe if keys are not updated.