Dividing array among fixed number of threads
arrays, c++, multithreading, split
Solution
Sorry for my quick and dirty code, but I think it does its job.
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 (a fork from @dasblinkenlight's)
The idea behind my code is:
`thread0` is responsible for the first `(NUMELEM/THREADCNT)+1` tasks; `thread1` is for the next `(NUMELEM/THREADCNT)+1` tasks...
Meanwhile the last thread is responsible for the last `(NUMELEM/THREADCNT)` tasks; the second last thread is for the second last `(NUMELEM/THREADCNT)` tasks...
Only the first `(NUMELEM%THREADCNT)` threads ("tougher" threads) have `(NUMELEM/THREADCNT)+1` tasks.
Problem
I want to split an array Data[ ] of variable size among fixed number of threads in a fair way Case 1: Divide Data[7] among 4 threads fairly ``` 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] ``` Presently my code divides the array unfairly Case 2: Divide Data[7] among 4 threads ``` 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] ``` Here is a the code which implements Case 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; } ``` I want solution to Case 1