[英]Parallelizing std::replace on std::deque
首先,我知道雙端隊列中的多個寫手不是很容易處理。 但是使用以下算法,我可以保證元素上沒有並發訪問。 該算法在塊中划分deque(它非常大,這就是我並行化它的原因)並且std :: replaces替換deque中的值。 問題是,在某些情況下,在替換任意值之后,該值似乎仍然存在(順便說一下:新值與舊值不同)。 可能是這個值沒有從cpu寄存器中同步到內存嗎? 這里的代碼:
std::deque<int*> _deque;
...
int threadsCount = 25;
int chunkSize = ceil((float) _deque.size() / (float) threadsCount);
std::vector<std::thread> threads;
for (int threadNo = 0; threadNo < threadsCount; threadNo++) {
std::uint64_t beginIndex = threadNo * chunkSize;
std::uint64_t endIndex = (threadNo + 1) * chunkSize;
if (endIndex > _deque.size()) {
endIndex = _deque.size();
}
std::deque<int*>::iterator beginIterator = _deque.begin() + beginIndex;
std::deque<int*>::iterator endIterator = _deque.begin() + endIndex;
threads.push_back(std::thread([beginIterator, endIterator, elementToReplace, elementNew] () {
std::replace(beginIterator, endIterator, elementToReplace, elementNew);
}));
}
for (int threadNo = 0; threadNo < threadsCount; threadNo++) {
threads[threadNo].join();
}
在該算法之后,有時(不確定)的情況是被替換的(elementToReplace)值仍然在deque中。
不要手動實現這樣的算法,只需傳遞適當的執行策略:
std::replace(std::execution::par, deque.begin(), deque.end(), elementToReplace, elementNew);
// ^^^^^^^^^^^^^^^^^^^
// executes the algorithm in parallel
請注意,您必須使用C ++ 17或更高版本進行編譯。
它看起來像一個競爭條件,但我無法重現它: http : //cpp.sh/5egzm這可能取決於你正在使用的deque實現,但它看起來很奇怪
僅供參考:由於上述算法崩潰且建議的執行策略在我的系統上仍然不可用,我使用了GNU parallel:
__gnu_parallel::replace(_deque.begin(), _deque.end(), elementToReplace, elementNew);
我會告訴你它是否有效以及性能統計數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.