我有一个 C 语言的程序,它将任意数量的文件作为命令行参数,并为每个文件计算 sha1sum。我正在使用 pthreads,这样我就可以利用我的所有 4 个核心。
目前,我的代码同时并行运行所有线程。 这是一个片段:
c = 0;
for (n = optind; n < argc; n++) {
if (pthread_create(&t[c], NULL, &sha1sum, (void *) argv[n])) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
c++;
}
c = 0;
for (n = optind; n < argc; n++) {
pthread_join(t[c], NULL);
c++;
}
显然,一次启动所有线程效率不高(或可扩展)。
确保只有 4 个线程在任何时候运行的最佳方法是什么?不知何故,我需要在开始时启动 4 个线程,然后在它完成后立即用新线程“替换”一个线程。
我该怎么做?
最佳答案
Obviously, it is not efficient (or scalable) to start all threads at once.
创建 4 个线程不一定能在 4 核机器上提供最佳性能。如果线程正在执行 IO 或等待某事,那么创建 4 个以上的线程也可能会带来更好的性能/效率。您只需要根据您的线程所做的工作和可能的迷你基准计算出一个大概的数字。
无论您选择什么数字(即线程数),您要查找的都是 thread pool .这个想法是创建固定数量的线程并在它们完成后立即为它们提供工作。
参见 C: What's the way to make a poolthread with pthreads?对于一个简单的骨架。这repo还显示了一个独立的示例(如果您要使用它,请检查许可证)。你可以在网上找到很多类似的例子。
关于c pthreads : run at most 4 threads concurrently at any time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386269/