Professional Documents
Culture Documents
Muhmmad Abdullah Cms Id: 298161 Oslab8
Muhmmad Abdullah Cms Id: 298161 Oslab8
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
int array[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int divide_array=0;
int array_sum[4]={0};
void *sum(void *arg){
for(int i=divide_array*4; i<(divide_array+1)*4;i++){
array_sum[divide_array] = array_sum[divide_array]+array[i];
}
divide_array++;
}
int main(){
pthread_t thread[4];
clock_t begin = clock();
for(int i=0; i<4; i++){
pthread_create(&thread[i],NULL,sum,(void*)NULL);
}
for(int i=0; i<4; i++){
pthread_join(thread[i],NULL);
}
int totalsum=0;
for(int i=0; i<4; i++){
totalsum+=array_sum[i];
}
clock_t end = clock();
double time_taken = (double)(end-begin)/CLOCKS_PER_SEC;
printf("%d\n",totalsum);
printf("Total time taken is %f seconds\n", time_taken);
}
Output:
TASK 2:
CODE:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
int array[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int array_part=0;
void *sum(void *arg){
int *arraysum=(int *)malloc(sizeof(int));
for(int i=array_part*4; i<(array_part+1)*4;i++){
*arraysum = *arraysum+array[i];
}
array_part++;
return arraysum;
}
int main(){
pthread_t thread[4];
int *mainsum=0;
int totalsum=0;
clock_t begin = clock();
for(int i=0; i<4; i++){
pthread_create(&thread[i],NULL,sum,(void*)NULL);
}
for(int i=0; i<4; i++){
pthread_join(thread[i],&mainsum);
totalsum=totalsum+*mainsum;
printf("local sum = %d\n",*mainsum);
}
clock_t end = clock();
double time_taken = (double)(end-begin)/CLOCKS_PER_SEC;
printf("global sum = %d\n",totalsum);
printf("Total time taken is %f seconds\n",time_taken);
}
Output:
TASK 3:
As you can see that the second approach is faster than the first one because in the second
approach we are working with local variables and they are stored in registers whereas global
variables are not.