99 lines
2.1 KiB
C
99 lines
2.1 KiB
C
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <sys/time.h>
|
|
#include <math.h>
|
|
|
|
|
|
#define TIMER_CLEAR (tv1.tv_sec = tv1.tv_usec = tv2.tv_sec = tv2.tv_usec = 0)
|
|
#define TIMER_START gettimeofday(&tv1, (struct timezone*)0)
|
|
#define TIMER_ELAPSED (double) (tv2.tv_usec-tv1.tv_usec)/1000000.0+(tv2.tv_sec-tv1.tv_sec)
|
|
#define TIMER_STOP gettimeofday(&tv2, (struct timezone*)0)
|
|
struct timeval tv1,tv2;
|
|
|
|
pthread_mutex_t myMutex;
|
|
|
|
#define MAX_THREADS 16
|
|
|
|
__thread double areaThread, areaThreadTotal;
|
|
__thread double myVal;
|
|
|
|
int NUM_THREADS;
|
|
double iterations;
|
|
int a = 0, b = 1;
|
|
double area, h;
|
|
double sumOfRectangles;
|
|
|
|
// returns square root
|
|
double func(double num)
|
|
{
|
|
return sqrt(1-pow(num,2));
|
|
}
|
|
|
|
void *protectedThreadFunc(void* argument)
|
|
{
|
|
int i;
|
|
int myId = (int)argument;
|
|
TIMER_START;
|
|
for(i=0;i<=iterations-1;i++)
|
|
{
|
|
areaThread=h*func(a+(i-1)*h);
|
|
areaThreadTotal+=areaThread;
|
|
}
|
|
|
|
pthread_mutex_lock (&myMutex);
|
|
sumOfRectangles=4*areaThreadTotal;
|
|
TIMER_STOP;
|
|
pthread_mutex_unlock (&myMutex);
|
|
|
|
}
|
|
|
|
int main(int argc, char * argv[])
|
|
{
|
|
TIMER_CLEAR;
|
|
if (argc < 3)
|
|
{
|
|
printf("Please specify the iterations or threads\n");
|
|
return -1;
|
|
}
|
|
area = 0;
|
|
int i;
|
|
|
|
iterations = atoi(argv[1]); // in other words this is n
|
|
|
|
NUM_THREADS = atoi(argv[2]);
|
|
|
|
h = (b-a)/iterations;
|
|
|
|
//creating pthread array
|
|
pthread_t myThreads[NUM_THREADS];
|
|
int status = 0;
|
|
|
|
|
|
//printf("Calling protected set of threads\n");
|
|
pthread_mutex_init(&myMutex, NULL);
|
|
//next set of threads will call a function that will update the variable protected
|
|
for(i=0;i<NUM_THREADS;i++)
|
|
{
|
|
status = pthread_create(&myThreads[i],NULL,protectedThreadFunc, (void*)i);
|
|
if(status)
|
|
{
|
|
printf("Error in creating the threads: %d\n",i);
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
for(i=0;i<NUM_THREADS;i++)
|
|
{
|
|
int retStatus = pthread_join(myThreads[i],NULL);
|
|
if(retStatus)
|
|
{
|
|
printf("Well..... some problem at thread id %d, error no: %d\n",i,retStatus);
|
|
}
|
|
}
|
|
pthread_mutex_destroy(&myMutex);
|
|
printf("Computed Sum for Rectangular Decomposition: %f\n", sumOfRectangles);
|
|
printf("Time elapsed = %f seconds\n", TIMER_ELAPSED);
|
|
return 0;
|
|
}
|