背景
我正在对图像中的行和列进行并行操作。我的图像是 8 位或 16 位像素,而我使用的是 64 位机器。
当我并行对列进行操作时,两个相邻列可能共享相同的 32 位int
或 64 位long
。基本上,我想知道是否可以安全地并行操作同一四字的各个字节。
最低限度的测试
我编写了一个最小的测试函数,但我无法使其失败。对于 64 位中的每个字节long
,我同时在有限阶域中执行连续乘法p
。我知道通过费马小定理 https://en.wikipedia.org/wiki/Fermat%27s_little_theorem a^(p-1) = 1 mod p
when p
是素数。我改变价值观a
and p
对于我的 8 个线程中的每一个,我执行k*(p-1)
的乘法a
。当线程完成时,每个字节应该为 1。事实上,我的测试用例通过了。每次运行时,我都会得到以下输出:
8
101010101010101
101010101010101
我的系统是Linux 4.13.0-041300-通用 x86_64与8 核 Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz。我编译了g++ 7.2.0 -O2并检查了装配体。我添加了“内循环”的程序集并对其进行了评论。在我看来,生成的代码是安全的,因为存储仅将低 8 位写入目标,而不是进行一些按位算术并存储到整个字或四字。 g++ -O3 生成类似的代码。
问题:
我想知道这段代码是否始终是线程安全的,如果不是,在什么情况下不会。也许我很偏执,但我觉得我需要一次对四字进行操作才能安全。
#include <iostream>
#include <pthread.h>
class FermatLTParams
{
public:
FermatLTParams(unsigned char *_dst, unsigned int _p, unsigned int _a, unsigned int _k)
: dst(_dst), p(_p), a(_a), k(_k) {}
unsigned char *dst;
unsigned int p, a, k;
};
void *PerformFermatLT(void *_p)
{
unsigned int j, i;
FermatLTParams *p = reinterpret_cast<FermatLTParams *>(_p);
for(j=0; j < p->k; ++j)
{
//a^(p-1) == 1 mod p
//...BEGIN INNER LOOP
for(i=1; i < p->p; ++i)
{
p->dst[0] = (unsigned char)(p->dst[0]*p->a % p->p);
}
//...END INNER LOOP
/* gcc 7.2.0 -O2 (INNER LOOP)
.L4:
movq (%rdi), %r8 # r8 = dst
xorl %edx, %edx # edx = 0
addl $1, %esi # ++i
movzbl (%r8), %eax # eax (lower 8 bits) = dst[0]
imull 12(%rdi), %eax # eax = a * eax
divl %ecx # eax = eax / ecx; edx = eax % ecx
movb %dl, (%r8) # dst[0] = edx (lower 8 bits)
movl 8(%rdi), %ecx # ecx = p
cmpl %esi, %ecx # if (i < p)
ja .L4 # goto L4
*/
}
return NULL;
}
int main(int argc, const char **argv)
{
int i;
unsigned long val = 0x0101010101010101; //a^0 = 1
unsigned int k = 10000000;
std::cout << sizeof(val) << std::endl;
std::cout << std::hex << val << std::endl;
unsigned char *dst = reinterpret_cast<unsigned char *>(&val);
pthread_t threads[8];
FermatLTParams params[8] =
{
FermatLTParams(dst+0, 11, 5, k),
FermatLTParams(dst+1, 17, 8, k),
FermatLTParams(dst+2, 43, 3, k),
FermatLTParams(dst+3, 31, 4, k),
FermatLTParams(dst+4, 13, 3, k),
FermatLTParams(dst+5, 7, 2, k),
FermatLTParams(dst+6, 11, 10, k),
FermatLTParams(dst+7, 13, 11, k)
};
for(i=0; i < 8; ++i)
{
pthread_create(threads+i, NULL, PerformFermatLT, params+i);
}
for(i=0; i < 8; ++i)
{
pthread_join(threads[i], NULL);
}
std::cout << std::hex << val << std::endl;
return 0;
}