-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork.c
More file actions
54 lines (41 loc) · 926 Bytes
/
fork.c
File metadata and controls
54 lines (41 loc) · 926 Bytes
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
#include<stdlib.h>
#include<stdio.h>
#include<stdint.h>
#include<pthread.h>
#include<signal.h>
#define MAX_PROCESS 8
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int offset;
void* add(void* data) {
int ret;
char line[10000];
pthread_mutex_lock(&lock);
FILE* text = fopen("temp.txt", "r");
fseek(text, offset, SEEK_SET);
ret = 0;
for (int k = 0; k < 2; k++) {
fgets(line, 10000, text);
ret += atoi(line);
}
offset = ftell(text);
fclose(text);
pthread_mutex_unlock(&lock);
return ret;
}
void main() {
pthread_t pthread[MAX_PROCESS];
void* data;
int error;
for (float i = MAX_PROCESS; i >= 1; i /= 2) {
for (int j = 0; j < i; j++) {
FILE* text = fopen("temp.txt", "a");
error = pthread_create(&pthread[j], NULL, add, NULL);
if (error < 0) printf("error");
else {
pthread_join(pthread[j], &data);
fprintf(text, "%d\n", (int)data);
fclose(text);
}
}
}
}