-
Notifications
You must be signed in to change notification settings - Fork 2
/
P2.c
103 lines (80 loc) · 2.38 KB
/
P2.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <math.h>
#include <pthread.h>
#include <time.h>
#define max_elem 1000000
typedef long long int ll;
typedef struct{
int start;
// seg_size = end - start + 1
int seg_size;
} sum_arg;
int *shared;
void * thread_sum(void * arg){
sum_arg* temp = (sum_arg*) arg;
ll* sum = malloc(sizeof(ll));
*sum = 0;
for(int i = temp->start; i < temp->start + temp->seg_size; i++){
*sum+=shared[i+1];
}
return (void*)sum;
}
void make_thread(int i, int t, int start, int seg_size, sum_arg *arg, pthread_t *threads){
arg[i].start = start;
arg[i].seg_size = seg_size;
pthread_create(&threads[i], NULL, &thread_sum, (void*) &arg[i]);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ./P2_final.out <thread numbers>\n");
exit(-1);
}
int thread_number = atoi(argv[1]);
ll sums_arr[max_elem] = {0};
int memID;
int memSize = sizeof(int)*(1000000 + 1);
key_t key = (key_t)69420;
memID = shmget(key, memSize, 0666|IPC_CREAT);
shared = shmat(memID, (void*)0, 0);
int num_int = shared[0];
clock_t start_time = clock();
sum_arg arg[thread_number];
pthread_t threads[thread_number];
int start=0;
int seg_size = num_int/thread_number;
// Creating Threads
for(int i = 0; i<thread_number; i++){
if(i==thread_number-1){
seg_size += num_int%thread_number;
}
make_thread(i, thread_number, start, seg_size, arg, threads);
start += seg_size;
}
ll* result;
ll sum = 0;
// Joining threads
for(int i = 0; i<thread_number; i++){
pthread_join(threads[i], (void**) &result);
sums_arr[i] = *result;
free(result);
}
for(int i = 0; i<thread_number; i++){
sum+=sums_arr[i];
}
clock_t stop_time = clock();
double elapsed_time = (double)(stop_time - start_time) / (double)CLOCKS_PER_SEC;
// storing logs in a txt file
// FILE *fp;
// fp = fopen("log_p2.txt", "w");
// if(fp == NULL)
// exit(-1);
// fprintf(fp, "%d %d %lf %lld\n", num_int, thread_number, elapsed_time, sum);
// fclose(fp);
return 0;
}