Home > Software design >  How to write parallelly into a container
How to write parallelly into a container

Time:01-19

I'm working with C 14 and I don't know how to write parallelly into a container with multi-threading.

Let's say I have such a map: std::map<int, int> mp {{1, 0}, {2, 0}, {3, 0}} and a function as below:

void updateValue(int& value) {
    value = xxx; // heavy calculation
}

Then I try to create three threads:

std::vector<std::thread> vec;
for (auto& ele : mp) {
    vec.emplace_back(std::thread(updateValue, std::ref(ele.second)));
}

However, the problem is that std::map is not thread-safe.

So it seems that I need to add a lock in the function updateValue. But if I do this, the function has to be called one by one, just like a single-thread.

It there some method to allow me to use multi-threading in this case?

CodePudding user response:

Your example is safe as-is, and doesn't require any additional synchronization.

[container.requirements.dataraces]/2 Notwithstanding [res.on.data.races], implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector<bool>, are modified concurrently.

  •  Tags:  
  • Related