概念,我怎麼能阻止使用一個tbb::parallel_for
裏面調用一個關鍵部分?關鍵部分少於20條指令,所以spin_mutex
是理想選擇。例如下面的虛擬代碼說明了情況:內parallel_for時TBB spin_mutex阻止一個關鍵部分
function() {
// I'm using lambda functions in parallel_for call here. The parallel_for
// is multithreading across the size of the vector customVec
tbb::parallel_for(
tbb::blocked_range<vector<CustomeType>::iterator>(customVec.begin(), customVec.end(), 1),
[&](tbb::blocked_range<vector<CustomType>::iterator> customVec) {
for (vector<CustomType>::iterator it = customVec.begin(); it != customVec.end(); it++) {
CustomType item = *it;
...
...
// This is the cross-functional call that each thread will call
// critical section is in-side the functionA
item->functionA(param1, param2);
}
...
...
}
);
...
...
}
與泛函:
functionA (Type1 param1, Type2 param2) {
if (conditionX) {
/* This file read is the critical section. So basically, need to
block multiple threads reading the same file to reduce I/O cost
and redundancy. Since file read can be stored in a global variable
that can be accessed in memory by other threads */
fileRead(filename); // Critical line that need to be protected
}
...
...
}
我正在掙扎是如何我可以設置spin_mutex
在functionA()
使得mutex
跨線程共享線程不會超越對方,試圖同時執行關鍵部分。
注意:假設function()
和functionA()
屬於兩個單獨的C++類和存在具有function()
和functionA()
作爲成員函數