I would like to know if the erasure of elements from list is considered to be "write" operation, i.e. is the erasure of elements in multiple threads thread-safe?
For example, I have a list with more than a 100k elements and, in order to speed up erasing elements from it based on some condition, I would like to split it into as many parts as there are available threads. Then, each thread would check its part and erase specific elements that satisfy some condition. Is this safe to do?
Here is my simple example (note: this is simplified case, I am aware of some edge cases):
#include <list>
#include <vector>
#include <thread>
#include <iostream>
#include <algorithm>
int main() {
constexpr size_t number_of_threads = 2;
std::list<unsigned int> elements = { 1, 2, 3, 4, 4, 5, 6, 7};
std::vector<std::thread> threads;
size_t elements_per_thread = elements.size() / number_of_threads;
for (size_t i = 0; i < number_of_threads; i++) {
auto elements_begin = std::next(std::begin(elements), i * elements_per_thread);
auto elements_end = std::next(elements_begin, elements_per_thread);
threads.emplace_back(
[&elements, elements_begin, elements_end]() {
elements.erase(std::remove_if(elements_begin, elements_end, [](unsigned int const& x) {
return x == 4;
}), elements_end);
}
);
}
for (auto& thread : threads) {
thread.join();
}
for (auto const& item : elements) {
std::cout << item << " " << std::endl;
}
return 0;
}
This would output correct result:
1
2
3
5
6
7
Thank you in advance