-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask1.c
More file actions
93 lines (75 loc) · 2.19 KB
/
task1.c
File metadata and controls
93 lines (75 loc) · 2.19 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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
// This is a silly glibc bug
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
#define THREAD_COUNT 10
void *writeToFile(void *threadID);
int main(int argc, char **argv) {
int ret[THREAD_COUNT];
pthread_t thread[THREAD_COUNT];
// seed rand
srand((unsigned int)time(NULL));
// Create THREAD_COUNT threads
for (int i = 0; i < THREAD_COUNT; i++) {
ret[i] = pthread_create(&thread[i], NULL, writeToFile, &i);
if (ret[i] != 0) {
fprintf(stderr, "ERROR %d: Cant create thread\n", ret[i]);
return EXIT_FAILURE;
}
}
// Close a thread with a chance of 50%
for (int i = 0; i < THREAD_COUNT; i++) {
if (rand() % 2) pthread_cancel(thread[i]);
}
// Wait for finish
for (int i = 0; i < THREAD_COUNT; i++) {
ret[i] = pthread_join(thread[i], NULL);
if (ret[i] != 0) {
fprintf(stderr, "ERROR %d: Cant join thread\n", ret[i]);
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
void cleanupHandler(void *arg) {
// close file descriptor
FILE *fp = (FILE *)arg;
if (fp != NULL) {
if (fclose(fp)) perror("cleanuphander");
}
}
void *writeToFile(void *threadID) {
int waitTime = 0;
char filename[12];
FILE *fptr = NULL;
// Sleep between 0 - 3 Seconds
waitTime = rand() % 4;
sleep(waitTime);
// format filename
sprintf(filename, "Thread%d.txt", *(int *)threadID);
/* will called when thread is canceled, calls pthread_exit or
pthread_cleanup_pop is executed with non-zero EXECUTE argument */
pthread_cleanup_push(cleanupHandler, fptr);
// try to open a file
fptr = fopen(filename, "rb+");
if (fptr == NULL) {
// file does not exist, create it
fptr = fopen(filename, "wb");
if (fptr == NULL) {
printf("Disc full or no permission\n");
return NULL;
}
}
// Write file
fprintf(fptr, "%d\n", (int)gettid());
// call cleanup handler
pthread_cleanup_pop(1);
// close
fclose(fptr);
return NULL;
}