college/ws2010/gdi3/p5/posix_threads.cpp
2011-10-18 11:14:08 +02:00

96 lines
2.9 KiB
C++

/*
* posix_threads.cpp
*
* Created on: 10.01.2011
* Author: mk
*/
#include <pthread.h> // POSIX-threads
#include <time.h> // time operations (to calculate the runtime)
#include <stdio.h> // standard IO operations (to print to console)
#include <stdlib.h> // general purpose standard library (to generate random numbers)
#define NUM_ELEMENTS 1000000 // number of array-elements to add
pthread_t* threads; // stores the posix-thread-objects
int* threadNums; // stores the thread-numbers
time_t beginCalc,endCalc; // used to calculate the runtime of the program
unsigned long a[NUM_ELEMENTS],b[NUM_ELEMENTS],c[NUM_ELEMENTS]; // arrays to add (c=a+b)
int numThreads; // number of threads to create
/*
* fills the arrays with random numbers between 0 and 9
*/
void fillArrays()
{
for(unsigned i=0;i<NUM_ELEMENTS;i++)
{
a[i] = rand() % 10;
b[i] = rand() % 10;
}
}
/*
* this function is called after a thread has been created by pthread_create
*/
void* addArrays(void* pThreadNum)
{
int* threadNum = (int*)pThreadNum;
printf("Thread %i started\n",*threadNum);
unsigned begin,end; // stores the first and last array index which this thread calculates
if(*threadNum == -1) // only one thread, so no POSIX-threads to create
{
begin = 0;
end = NUM_ELEMENTS;
}
else // calculate the first and last array index this thread has to calculate
{
begin = (NUM_ELEMENTS/numThreads)**threadNum;
end = (NUM_ELEMENTS/numThreads)*(*threadNum+1);
}
for (unsigned j=0;j<10000;j++) // run 10.000 times to get a runtime long enough to compare
for (unsigned i=begin;i<end;i++)
c[i] = a[i] + b[i]; // add array elements
}
int main(int argc, char* argv[])
{
if(argc!=2)
{
printf("error! first parameter should be: number of threads\n");
return -1;
}
numThreads = atoi(argv[1]); // get number of threads from the first parameter
fillArrays(); // fill the arrays with random numbers
time(&beginCalc); // store the time at the beginning of the calculation
if(numThreads==1) // no POSIX-threads need to be created
{
int noThreads = -1;
addArrays((void*)&noThreads);
}
else if(numThreads>1)
{
threads = (pthread_t*)malloc(numThreads*sizeof(pthread_t)); // reserve memory for the threads
threadNums = (int*)malloc(numThreads*sizeof(int)); // reserve memory for the thread-numbers
for (unsigned i=0;i<numThreads;i++)
{
threadNums[i] = i;
pthread_create(&threads[i],NULL,addArrays,(void *)&threadNums[i]); // create thread
}
// wait for termination of all threads
for(unsigned i=0;i<numThreads;i++)
pthread_join(threads[i],NULL);
// free memory
free(threads);
free(threadNums);
}
else
{
printf("error! number of threads must be positive\n");
return -1;
}
time(&endCalc); // store the time at the end of the calculation
double timePassed = difftime(endCalc,beginCalc); // calculate the passed time between beginning and end of the calculation
printf("%f seconds passed\n",timePassed);
return 0;
}