【问题标题】:Why does using multiple threads result in slower execution?为什么使用多个线程会导致执行速度变慢?
【发布时间】: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 &lt; 321536-1; i += threadCount 正在交错线程。而是在单独的段上运行每个线程,这样它们就不会都在缓存中访问相同的数据。

标签: c multithreading


【解决方案1】:

首先,锁序列化所有identicalVoxelGroupsCount增量。使用更多线程不会加快这部分的速度。相反,它会变慢,因为 cache-line bouncing:包含锁和增量变量的缓存行将从一个内核串行移动到另一个内核(参见:cache coherence protocols)。这通常比按顺序执行所有工作要慢得多,因为将缓存线从一个内核移动到另一个内核会引入相当大的延迟。您不需要锁。您可以改为增加一个局部变量,然后只执行一次最终减少(例如,通过更新getIdenticalVoxelGroupsCount 末尾的原子变量)。

此外,循环迭代的交错效率不高,因为大多数包含voxelGroups 的缓存行将在线程之间共享。这不像第一点那么重要,因为线程只读取缓存行。尽管如此,这仍会增加内存吞吐量并导致瓶颈。一种更有效的方法是将迭代拆分为相对较大的连续块。将块拆分为中等粒度的切片以更有效地使用缓存可能会更好(尽管这种优化与并行化策略无关)。

请注意,您可以使用 OpenMP 在 C 语言中轻松高效地执行此类操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多