tbb parallel_reduce 用于 OpenMP 缩减的片段

tbb parallel_reduce for a snippet of OpenMP reduction

本文关键字:片段 OpenMP 用于 parallel reduce tbb      更新时间:2023-10-16

我有以下 OpenMP 的代码片段,我知道它肯定可以正常工作。

char cipherChar=plainText[charLoop];
#pragma omp parallel for reduction(^:cipherChar)
for(keyLoop=0;keyLoop<numKeys;keyLoop++) {
    cipherChar = cipherChar ^ getBit( &(keyList[keyLoop]), charLoop);
}
cypherText[charLoop]=cipherChar;

但是当我尝试用 tbb 编写此代码时,我没有得到正确的输出

char cipherChar=plainText[charLoop];
cipherChar ^= tbb::parallel_reduce(tbb::blocked_range<int>(0, numKeys), cipherChar,
[&](const tbb::blocked_range<int>& r, char c) -> char {
            char result = c;
            for(int i = r.begin(); i <= r.end(); i++) {
                    result ^= getBit( &(keyList[i]), charLoop);
            }
            return result;
    },
    [](char a, char b) {
            return a ^ b;
    }
);
cypherText[charLoop]=cipherChar;

谁能告诉我我在上面的 tbb 代码中可能做错了什么,我得到了错误的结果?

parallel_reduce的第二个参数(blocked_range后面的参数(应该是所用缩减操作的标识值。实现使用此值来初始化累加器。对于独占 OR,标识值为 0。此外,标识值的类型必须与结果的类型匹配。

所以,你的电话应该是

cipherChar ^= tbb::parallel_reduce(
    tbb::blocked_range<int>(0, numKeys),
    char(0), // <- identity for XOR
    body_lambda,
    reduction_lambda
);