我目前正在学习pthreads
C 并遇到了错误共享的问题。我想我理解它的概念,并且我尝试过一些实验。
下面是我一直在玩的一个简短的程序。最终,我将把它改成一个程序来获取大量整数并并行求和。
#include <stdio.h>
#include <pthread.h>
#define THREADS 4
#define NUMPAD 14
struct s
{
int total; // 4 bytes
int my_num; // 4 bytes
int pad[NUMPAD]; // 4 * NUMPAD bytes
} sum_array[4];
static void *worker(void * ind) {
const int curr_ind = *(int *) ind;
for (int i = 0; i < 10; ++i) {
sum_array[curr_ind].total += sum_array[curr_ind].my_num;
}
printf("%d\n", sum_array[curr_ind].total);
return NULL;
}
int main(void) {
int args[THREADS] = { 0, 1, 2, 3 };
pthread_t thread_ids[THREADS];
for (size_t i = 0; i < THREADS; ++i) {
sum_array[i].total = 0;
sum_array[i].my_num = i + 1;
pthread_create(&thread_ids[i], NULL, worker, &args[i]);
}
for (size_t i = 0; i < THREADS; ++i) {
pthread_join(thread_ids[i], NULL);
}
}
我的问题是,是否可以在不使用填充的情况下防止虚假共享?这里struct s
的大小为 64 字节,因此每个结构都在自己的缓存行上(假设缓存行是 64 字节)。我不确定如何在没有填充的情况下实现并行性。
另外,如果我要对一个大小在 1000-50,000 字节之间的数组求和,我该如何防止错误共享?我可以使用类似的程序来填充它吗?我目前的想法是将大数组中的每个 int 放入一个数组中struct s
,然后使用并行性对其求和。但是我不确定这是否是最佳解决方案。