在固定数量的线程之间划分数组

时间:2014-02-07 18:59:10

标签: c++ arrays multithreading split

我希望以合理的方式在固定数量的线程中拆分可变大小的数组 Data []

案例1:将4个线程中的数据[7]公平分配

Thread ID 0: Data[0], Data[1]
Thread ID 1: Data[2], Data[3]
Thread ID 2: Data[4], Data[5]
Thread ID 3: Data[6]

目前我的代码不公平地划分数组

案例2:在4个主题中划分数据[7]

Thread ID 0: Data[0]
Thread ID 1: Data[1]
Thread ID 2: Data[2]
Thread ID 3: Data[3], Data[4], Data[5], Data[6]

以下是实施案例2 的代码。

#include <iostream>
using namespace std;

const unsigned int NUMELEM = 7;
const unsigned int THREADCNT = 4;

unsigned int elemPerThread = NUMELEM/THREADCNT;
unsigned int remElements = NUMELEM % THREADCNT;

int Data[NUMELEM];

void DoStuff( unsigned int const& thid )
{
    unsigned int startIndex = thid*elemPerThread;
    unsigned int endIndex = startIndex + elemPerThread;

    cout<<"Thread ID "<<thid<<": ";
    for( unsigned int index = startIndex; index != endIndex; index++ )
    {
        cout<<"Data["<<index<<"], ";
    }

    if( (thid+1) == THREADCNT )
    {
        for( unsigned i = 0; i!= remElements; i++)
        {
            cout<<"Data["<<endIndex + i<<"], ";
        }
    }

    cout<<endl;
}

int main()
{
    for( unsigned int thid = 0; thid != THREADCNT; thid++)
    {
        // TBU: Make multithreaded
        DoStuff( thid );
    }

    return 0;
}

我想解决案例1

1 个答案:

答案 0 :(得分:2)

对不起我的快速而肮脏的代码,但我认为它可以完成它的工作。

void DoStuff( unsigned int const& thid )
{
    cout<<"ThID:"<<thid<<endl;
    const unsigned numTasks = NUMELEM/THREADCNT, numTougherThreads = NUMELEM%THREADCNT;
    for( unsigned int index0 = (thid < numTougherThreads ? thid * (numTasks+1) : NUMELEM - (THREADCNT - thid) * numTasks), index = index0; index < index0 + numTasks + (thid < numTougherThreads) ; ++index)
    {
        cout<<"Data["<<index<<"], ";
    }
    cout<<endl;
}

http://ideone.com/3CeMm8(来自@ dasblinkenlight的分叉)

我的代码背后的想法是:

  1. thread0负责第一个(NUMELEM/THREADCNT)+1任务; thread1适用于下一个(NUMELEM/THREADCNT)+1任务...

  2. 同时最后主题负责最后 (NUMELEM/THREADCNT)个任务; 倒数第二主题针对倒数第二 (NUMELEM/THREADCNT)个任务...

  3. 只有第一个(NUMELEM%THREADCNT)个主题(“更强”的主题)才有(NUMELEM/THREADCNT)+1个任务。