【发布时间】:2021-12-14 01:39:37
【问题描述】:
我使用的是 MacBook Air M1 2020、Apple M1 7 核 GPU、RAM 8GB。
问题: 我正在比较按顺序执行大约需要 11 分钟的数组对。奇怪的是,我投入工作的线程越多,完成所需的时间就越多(即使不使用互斥锁)。到目前为止,我尝试使用 2 个线程和 4 个线程运行它。
可能是什么问题?我假设使用 4 个线程会更有效,因为我有 7 个内核可用,而且执行时间(对我而言)似乎足够长,可以补偿处理多个线程造成的开销。
这是我发现与此问题相关的部分代码:
int const xylen = 1024;
static uint8_t voxelGroups[321536][xylen];
int threadCount = 4;
bool areVoxelGroupsIdentical(uint8_t firstArray[xylen], uint8_t secondArray[xylen]){
return memcmp(firstArray, secondArray, xylen*sizeof(uint8_t)) == 0;
}
void* getIdenticalVoxelGroupsCount(void* threadNumber){
for(int i = (int)threadNumber-1; i < 321536-1; i += threadCount){
for(int j = i+1; j < 321536; j++){
if(areVoxelGroupsIdentical(voxelGroups[i], voxelGroups[j])){
pthread_mutex_lock(&mutex);
identicalVoxelGroupsCount++;
pthread_mutex_unlock(&mutex);
}
}
}
return 0;
}
int main(){
// some code
pthread_create(&thread1, NULL, getIdenticalVoxelGroupsCount, (void *)1);
pthread_create(&thread2, NULL, getIdenticalVoxelGroupsCount, (void *)2);
pthread_create(&thread3, NULL, getIdenticalVoxelGroupsCount, (void *)3);
pthread_create(&thread4, NULL, getIdenticalVoxelGroupsCount, (void *)4);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_join(thread4, NULL);
// some code
}
【问题讨论】:
-
你是如何编译这个的?它被标记为 C,但
int const xylen = 1024;和static uint8_t voxelGroups[321536][xylen];应该在 C 中给你一个错误,因为xylen不是 integer constant expression,使voxelGroups成为一个可变长度数组,在静态或文件范围内是不允许的. -
可能任务经常自己阻塞 - 因此执行速度较慢
-
那么如何通过添加线程来加快这段代码的速度呢?我所看到的,每个线程都在做同样的循环——更多的线程更多的循环。
-
FWIW,与创建四个新线程的开销相比,几十万次迭代并不算多,这可能涉及通过
mmap()操作创建它们的堆栈。 -
int i = (int)threadNumber-1; i < 321536-1; i += threadCount正在交错线程。而是在单独的段上运行每个线程,这样它们就不会都在缓存中访问相同的数据。
标签: c multithreading