如何为固定数量的线程计算均匀分布的作业数量?

Tra*_*cer 2 c++

让我们假设我有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 个线程时,我会得到以下分布:

  • 线程 1:任务 1
  • 主题 2:任务 2
  • 主题 3:任务 3
  • 主题 4:任务 4
  • 主题 5:任务 5
  • 主题 6:任务 6
  • 主题 7:任务 7
  • 线程 8:任务 8-15

与其他线程相比,最后一个线程将执行许多任务,这就是为什么我想将此分布修复为如下所示:

  • 线程 1:任务 1-2
  • 主题 2:任务 3-4
  • 线程 3:任务 5-6
  • 线程 4:任务 7-8
  • 线程 5:任务 9-10
  • 主题 6:任务 11-12
  • 线程 7:任务 13-14
  • 主题 8:任务 15

我需要帮助修复上面的代码以获得这种结果,其中每个线程都有相似数量的任务要执行。谢谢。

编辑:由于@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)

sha*_*ton 6

要提前计算每个线程的任务数,可以使用以下公式:

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。