Is there a way to update and erase in a thread-safe way? #287
-
I'm using Is there a correct way to do this without running into thread-safety issues? I can think of two solutions, but I feel they are both imperfect.
Is there anything like " |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @VarunSaini02! Here are some conceptual clarifications:
my_map = ...; Regardless of what you put in the One solution to the problem highlighted in 2) is to use mutexes to protect accesses to the map. But even better, you can use auto my_map = immer::atom<immer::map<string, string>>{}; And in one thread read it and in another thread update it like this: my_map.update([](auto value) {
if (auto item_p = item.find(some_item); item_p) {
if (some_condition(item_p))
return std::move(value).erase(some_item);
else
return std::move(value).set(some_item, transform(*item_p));
}
return value;
}); Everything that you do in the Does this make sense? Btw, I see that you work at @Roblox. That's pretty cool :) Are you using Immer for projects there? I would be interested to learn more about your use-case, please throw a message: [email protected] |
Beta Was this translation helpful? Give feedback.
Hi @VarunSaini02!
Here are some conceptual clarifications:
The
erase
andupdate
functions, like every singleconst
method in an Immer container is thread safe. They are "thread safe" also when applied in multiple steps. I wouldn't advise to mutate the map inside theupdate()
function as it can lead to problems, but a multi-step approach should both be safer and easier to understand.The only method that is not thread-safe in an
immer::map
is assignment, theoperator=
. This means that you can not, in an unprotected manner, read a variable of typeimmer::map
and the same time write to it in another thread. This means that if you have a variable calledmy_map
that is shared across thread…