1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
struct ArrayData
{
int *theArray;
int lowerBound;
int upperBound;
int sum;
};
int Calculate(void *lpData)
{
ArrayData &data = reinterpret_cast<ArrayData&>(*lpData);
data.sum = 0;
for (int i = data.lowerBound; i <= data.upperBound; i++)
data.sum += data.theArray[i];
return 0;
}
//Now you need to create one thread per core.
//I only program for Windows, so I don't know about pthread.h or *nix-based threading.
//This is an array of ArrayData structures that hold the data and the results.
//Needs to be accessible from several functions, so I declare it here.
ArrayData *workingSet;
int workingSetSize;
//Windows-specific: Thread handles for later.
HANDLE *threadHandles;
const int totalElements = 12;
void StartWorkers()
{
// See http://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine for the number of cores in a PC.
SYSTEM_INFO si;
GetSystemInfo(&si);
workingSetSize = si.dwNumberOfProcessors;
workingSet = new ArrayData[workingSetSize];
workingSet[0].theArray = someArray; //Dunno your array variable, so substitute here as appropriate.
workingSet[0].lowerBound = 0;
workingSet[0].upperBound = totalElements / workingSetSize;
int i = 1;
while (i < workingSetSize)
{
workingSet[i].theArray = someArray; //Same as a few lines above.
workingSet[i].lowerBound = workingSet[i - 1].upperBound + 1;
workingSet[i].upperBound = workingSet[i].lowerBound + totalElements / workingSetSize;
}
// This can be improved. Up to you.
workingSetSize[workingSetSize - 1].upperBound += totalElements % workingSetSize;
//Now the data for each thread is ready. Start the threads.
//This is Windows cuz I know Windows only.
//If you use MS C++, use _beginthreadex() instead of CreateThread().
DWORD dwThreadID;
threadHandles = new HANDLE[workingSetSize];
for (i = 0; i < workingSetSize; i++)
threadHandles[i] = CreateThread(NULL, 0, &Calculate, &workingSet[i], 0, &dwThreadID);
}
....
//Now in the main function or some other function, after calling StartWorkers(), it must wait for
//all threads to finish.
//Again, Windows-specific:
WaitForMultipleObjects(workingSetSize, threadHandles, TRUE, INFINITE);
....
|