-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
493 lines (387 loc) · 13.1 KB
/
main.c
File metadata and controls
493 lines (387 loc) · 13.1 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include "functions.h"
#include "dynamicarray.h"
#include <string.h>
#define TOH_DISK 20 // Number of disk used in tower of hanoi, number of instructions = 2 ^ TOH_DISK
#define PRIMEMAX 10000000 // Prime numbers are being found up to PRIMEMAX
typedef struct {
long taskid;
clock_t start;
clock_t end;
} Thread_data;
//Global variables
FILE * fptr;
sem_t filelock;
sem_t primelock;
sem_t fibonaccilock;
sem_t tohlock;
/*
* Finds the primenumbers up to PRIMEMAX, and writes them into a file.
* File name: prime.txt
* returns 1 if successful
* returns -1 if unable to open file.
*/
void * primeWr(void * t){
//Lock the primeRd thread, so it waits for this thread to be done writing.
sem_wait(&primelock);
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
long retval = 0;
char * str;
Array numbers;
initArray(&numbers, 2, 15);
//generate primenumbers from 0 to the maximum number in the rand() function.
//Time for the following process about 22 sec. on Ryzen 5 cpu.
for (long i = 0; i < PRIMEMAX; i++){
if(isPrimeRt(i) == 1) {
str = (char *) calloc(numbers.strsize, sizeof(char));
sprintf(str, "%ld", i);
addString(&numbers, str);
}
}
//Wait until file is open for writing.
sem_wait(&filelock);
// Open the file and write to it.
if((fptr = fopen("prime.txt", "w")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*)retval);
}
for (unsigned long int i = 0; i < numbers.used; i++){
fprintf(fptr, "%s\n", numbers.array[i]);
}
fclose(fptr);
//Free the locks and variables.
sem_post(&primelock);
sem_post(&filelock);
freeArray(&numbers);
//Set return value and set process end time.
retval = 1;
data->end = clock();
pthread_exit((void *) retval);
}
/*
* Thread to read the prime numbers from file, and generate random numbers and figure out if they are primenumbers.
* File name: prime.txt
* Returns number of random generated primenumbers
* Returns -1 if failing to open the file.
*/
void * primeRd(void * t){
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
time_t t1;
long retval = 0;
long psize;
Array numbers;
initArray(&numbers, 2, 15);
char * str;
// Wait for the primeWr thread to be done, and for the file to be unused.
sem_wait(&primelock);
sem_wait(&filelock);
//Open the file and read the data into an dynamic array.
if((fptr = fopen("prime.txt", "r")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*) retval);
}
while (!feof(fptr)){
str = (char *) calloc(numbers.strsize, sizeof(char));
fscanf(fptr,"%s",str);
addString(&numbers, str);
}
fclose(fptr);
//Free the locks, for others to use.
sem_post(&primelock);
sem_post(&filelock);
//Convert the strings to integers.
int * primes = (int *) calloc(numbers.used, sizeof(int));
for(unsigned long int i = 0; i < numbers.used; i++){
char * tmp;
primes[i] = strtol(numbers.array[i], &tmp, 10);
}
psize = numbers.used;
//Free the dynamic array.
freeArray(&numbers);
//Seed the RNG.
srand((unsigned int) time(&t1));
//Create a number of random numbers and figure out if they are primenumbers.
//using linear search to add a bit more processing time. Can be changed to binary search.
retval = 0;
for(int i = 0; i < 1000; i++){
int random = rand() % PRIMEMAX;
for (int j = 0; j < psize; j++){
if (random == primes[j]){
retval++;
}
}
}
// Free the variables and get the end process time.
free(primes);
data->end = clock();
pthread_exit((void *) retval);
}
/*
* Creates the fibonacci sequence of numbers and writes them into a text file.
* File name: fibonacci.txt
* Returns 1 if successful
* Returns -1 if failed to open the file.
*/
void * fibonacciWr(void * t){
// Locks the fibonacciRd thread, so it waits for the writer to be done.
sem_wait(&fibonaccilock);
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
long retval = 0;
long n = RAND_MAX;
Array numbers;
initArray(&numbers, 2, 15);
// Create the fibonacci sequence of numbers using recursion.
fibonacci(&numbers, 0, 1, n);
// Lock the file for use by this thread.
sem_wait(&filelock);
// Open the file and write the sequence of numbers into it.
if((fptr = fopen("fibonnaci.txt", "w")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*)retval);
}
for (unsigned long int i = 0; i < numbers.used; i++){
fprintf(fptr, "%s\n", numbers.array[i]);
}
fclose(fptr);
//Free the locks and the dynamic array.
sem_post(&fibonaccilock);
sem_post(&filelock);
freeArray(&numbers);
// Get end time and return.
data->end = clock();
retval = 1;
pthread_exit((void *)retval);
}
/*
* Thread to read an fibonacci sequence of numbers from a file, and generate random numbers and figure out if they are a part of the sequence
* File name: fibonacci.txt
* Returns number of fibonacci numbers randomly generated.
* Returns -1 if failed to open the file.
*/
void * fibonacciRd(void * t){
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
long retval = 0;
long fnsize;
time_t time1;
Array numbers;
int * fibnum;
char * str;
initArray(&numbers, 2, 15);
// Wait for the fibonacciWr thread to be done, and for the file to be unused.
sem_wait(&fibonaccilock);
sem_wait(&filelock);
// Open the file and read the data into an dynamic array.
if((fptr = fopen("fibonnaci.txt", "r")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*) retval);
}
while (!feof(fptr)){
str = (char *) calloc(numbers.strsize, sizeof(char));
fscanf(fptr,"%s",str);
addString(&numbers, str);
}
fclose(fptr);
// Free the locks
sem_post(&fibonaccilock);
sem_post(&filelock);
// Convert the strings into an array of integers.
fibnum = (int *) calloc(numbers.used, sizeof(long));
for(int i = 0; i < numbers.used; i++){
char * tmp;
fibnum[i] = strtol(numbers.array[i], &tmp, 10);
}
fnsize = numbers.used;
// Free the dynamic array of strings.
freeArray(&numbers);
//Seed the RNG.
srand((unsigned int) time(&time1));
// Generate random numbers and figure out if they are fibonacci numbers.
retval = 0;
for(int i = 0; i < 1000000; i++){
int random = rand();
if(bisearch(fibnum, random, fnsize) >= 0){
retval++;
}
}
// Free heap data and get the end process time.
free(fibnum);
data->end = clock();
pthread_exit((void *) retval);
}
void * towerOfHanoiWr(void * t){
// Locks the fibonacciRd thread, so it waits for the writer to be done.
sem_wait(&tohlock);
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
unsigned long int strsize = 100;
Array ins;
long retval = 0;
int n = TOH_DISK;
initArray(&ins, 2, strsize);
// Run tower of hanoi function to get an list of instruction for the tower of hanoi player.
// Uses recursion to generate the list.
towerOfHanoi(&ins, n, 'A', 'C', 'B');
//Lock the file, so it can be used for writing.
sem_wait(&filelock);
// Open the file and write the list of instructions into the file.
if((fptr = fopen("toh.txt", "w")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*)retval);
}
for (unsigned long int i = 0; i < ins.used; i++){
fprintf(fptr, "%s\n", ins.array[i]);
}
fclose (fptr);
//Free the locks.
sem_post(&tohlock);
sem_post(&filelock);
//Free array of strings and get the end time.
freeArray(&ins);
data->end = clock();
retval = 1;
pthread_exit((void *) retval);
}
/*
* Thread reads an list of instructions, and solves an tower of hanoi.
* Returns 1 if it could use the instruction to solve the tower.
* Returns 0 if it could not solve the tower using the instructions.
* Returns -1 if it could not open the file.
*/
void * towerOfHanoiRd(void * t){
// Initialization phase.
// start gathering timing data.
Thread_data * data = (Thread_data *) t;
printf("Starting thread %ld\n", data->taskid);
data->start = clock();
long retval = 0;
int n = TOH_DISK;
char * str;
Array ins;
initArray(&ins, 2, 100);
//Wait for the towerOfHanoiWr to be done writing the instructions into the file.
sem_wait(&tohlock);
sem_wait(&filelock);
//Open the file, and read the data into an dynamic array of strings.
if((fptr = fopen("toh.txt", "r")) == NULL) {
puts("File couldn't be opened");
retval = -1;
data->end = clock();
pthread_exit((void*) retval);
}
while (!feof(fptr)){
str = (char *) calloc(ins.strsize, sizeof(char));
fgets(str, ins.strsize, fptr);
addString(&ins, str);
}
fclose(fptr);
// Free the locks.
sem_post(&tohlock);
sem_post(&filelock);
//Solve the tower of Hanoi, using the list of instructions.
retval = tOHPlayer(&ins, n);
//Free the array, and get the end time.
freeArray(&ins);
data->end = clock();
pthread_exit((void *) retval);
}
int main() {
// Initialization phase
int num_t = 6;
// Using an list of function pointers to pass to the thread creater.
void * (*fun_ptr_arr[])(void *) = {primeWr, primeRd, fibonacciWr, fibonacciRd, towerOfHanoiWr, towerOfHanoiRd};
void * retval [num_t];
double time_spent [num_t];
double seq_total = 0;
Thread_data data [num_t];
pthread_attr_t attr;
pthread_t threads [num_t];
int rc, t;
// Initialize the locks for the use of the threads.
sem_init(&filelock, 0, 3);
sem_init(&tohlock, 0, 1);
sem_init(&fibonaccilock, 0, 1);
sem_init(&primelock, 0, 1);
//Create the joinable attributes for the threads.
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
//Create the threads
for(t = 0; t < num_t; t++) {
data[t].taskid = t;
rc = pthread_create(&threads[t], &attr, fun_ptr_arr[t], (void *) &data[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// Get the time from the creation of all threads, to the time it takes for them all to join.
clock_t begin = clock();
//Free attribute and wait for the other threads
pthread_attr_destroy(&attr);
//Wait for the threads to join.
for (t = 0; t < num_t; t++){
rc = pthread_join(threads [t], &retval[t]);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Value returned from thread %d: %ld\n", t, (long) retval[t]);
}
clock_t end = clock();
// Calculate the processing times of the individual threads.
double main_time = (double) (end - begin)/CLOCKS_PER_SEC;
for (int i = 0; i < num_t; i++){
if(i % 2 == 1){
time_spent[i] = ((double) (data[i].end - data[i].start) / CLOCKS_PER_SEC) - time_spent[i-1];
} else {
time_spent[i] = (double) (data[i].end - data[i].start) / CLOCKS_PER_SEC;
}
seq_total += time_spent[i];
printf("Thread %ld process time was %lf sec.\n", data[i].taskid, time_spent[i]);
}
/*
* For fair comparison between the total time without multithreading,
* i have subtracted the writing time from the reader threads,
* since they have to wait for writers to be done.*/
printf("\nTime it took for all threads to join: %lf sec.\n", main_time);
printf("\nTime it would have taken without multithreading: %lf sec.\n", seq_total);
printf("\nPercentage difference between the two: %lf %%\n", 100-((main_time/seq_total)*100));
//Remember to destroy all the semaphores before ending the main.
sem_destroy(&filelock);
sem_destroy(&tohlock);
sem_destroy(&fibonaccilock);
sem_destroy(&primelock);
pthread_exit(NULL);
}