'How to Parallelize C++ Vector Writes
std::vector<size_t> vector;
std::vector<size_t> v_vector;
Hello, Suppose 2 threads are reading from "vector" and compute a simple math operation and then save the result in v_vector.
Using a global mutex to ensure that the threads are locking and unlocking the same mutex how would one parallelize this so that the 2 threads are reading, computing the math operation, and storing the content in v_vector faster than a single thread.
Ideas so far, divide vector.size() in half. Have thread 1 iterate from 0 to vector half, and have the 2nd thread iterate from vector half to vector end. (however, there seems to be a write access violation from this, not sure why as the vector writes for both threads are protected by a mutex)
The order in which the threads push values into v_vector does not matter.
Any other ideas or if you see any logic issues would be greatly appreciated!
Solution 1:[1]
As long as no thread resizes the vectors you can have many threads reading and writing as you want. The vector won't care.
All you have to watch out for is that the threads don't use the same elements of each vector or you will have to add mutexes to synchronize access.
Splitting the vector in half using v.begin()', v.end()andstd::midpoint` is the best way to go if the work per element is roughly constant.
So run your threads with:
{
v_vector.resize(vector.size());
auto mid = std::midpoint(vector.begin(), vector.end());
auto v_mid = std::midpoint(v_vector.begin(), v_vector.end());
std::jthread thread1(compute, vector.begin(), mid, v_vector.begin());
std::jthread thread2(compute, mid, vector.end(), v_mid);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
