让我们假设我有tasks许多任务和threads运行它们的线程数。每个线程只能运行一次,所以我想通过现有线程平均分配这些任务。为了计算每个线程的任务数,我编写了这个简单的应用程序:
#include <iostream>
using namespace std;
int main(){
int tasks = 15;
int threads = 8;
if(tasks < threads)
threads = tasks;
int tasksPerThread = tasks / threads;
for (int i = 0, start = 1; i < threads; i++) {
start = tasksPerThread * i + 1;
int end = start + tasksPerThread - 1;
if (i == threads - 1 && end < tasks)
end = tasks;
if(start == end)
cout << "Thread " << i + 1 << ": task " << end << endl;
else
cout << "Thread " << i + 1 << ": task " << start << "-" << end << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当有 16 个任务和 8 个线程时,每个线程将获得 2 个任务。但是,在这种情况下,当有 15 个任务和 8 个线程时,我会得到以下分布:
与其他线程相比,最后一个线程将执行许多任务,这就是为什么我想将此分布修复为如下所示:
我需要帮助修复上面的代码以获得这种结果,其中每个线程都有相似数量的任务要执行。谢谢。
编辑:由于@shananton 的公式,这是解决方案。
int tasks = 15;
int threads = 8;
if (tasks < threads)
threads = tasks;
int start, usedTasks = 0, tasks_for_this_thread = 0;
for (int i = 0; i < threads; i++) {
usedTasks += tasks_for_this_thread;
start = usedTasks + 1;
tasks_for_this_thread = tasks / threads + (i < tasks % threads);
int end = start + tasks_for_this_thread - 1;
if (start == end)
cout << "Thread " << i + 1 << ": task " << end << endl;
else
cout << "Thread " << i + 1 << ": task " << start << "-" << end << endl;
}
Run Code Online (Sandbox Code Playgroud)
要提前计算每个线程的任务数,可以使用以下公式:
int tasks = 10;
int threads = 3;
for (int i = 0; i < threads; ++i) {
int tasks_for_this_thread = tasks / threads + (i < tasks % threads);
// do whatever you want to
}
Run Code Online (Sandbox Code Playgroud)
例如,对于 10 个任务和 3 个线程,它将任务分配为 4、3、3。