从概念上讲,如何使用tbb::parallel_for阻止tbb:spin_mutex调用中的关键部分?关键部分少于20条指令,因此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);
            }

            ...
            ...
        }
    );

    ...
    ...
}


和功能A:

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()作为成员函数的两个类之间没有基于类的继承。

最佳答案

您可能要考虑在函数内使用静态spin_mutex

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 */

        // A static mutex that is shared across all invocations of the function.
        static tbb::spin_mutex mtx;
        // Acquire a lock
        tbb::spin_mutex::scoped_lock lock(mtx);
        fileRead(filename); // Critical line that need to be protected
    }
    ...
    ...
}


请注意,它仅适用于C ++ 11及更高版本(因为您需要“魔术静态”,即静态变量初始化的线程安全性)。

关于c++ - TBB spin_mutex在parallel_for内部以阻止关键部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45868404/

10-12 21:19