-
Notifications
You must be signed in to change notification settings - Fork 0
/
tps.c
117 lines (93 loc) · 2.49 KB
/
tps.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
https://powcoder.com
代写代考加微信 powcoder
Assignment Project Exam Help
Add WeChat powcoder
https://powcoder.com
代写代考加微信 powcoder
Assignment Project Exam Help
Add WeChat powcoder
#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tps.h>
#include <sem.h>
char *msg1 = "Hello world!\n";
char *msg2 = "hello world!\n";
sem_t sem1, sem2;
void* thread2(void* arg)
{
char *buffer = malloc(TPS_SIZE);
/* Create TPS and initialize with *msg1 */
tps_create();
tps_write(0, TPS_SIZE, msg1);
/* Read from TPS and make sure it contains the message */
memset(buffer, 0, TPS_SIZE);
tps_read(0, TPS_SIZE, buffer);
assert(!memcmp(msg1, buffer, TPS_SIZE));
printf("thread2: read OK!\n");
/* Transfer CPU to thread 1 and get blocked */
sem_up(sem1);
sem_down(sem2);
/* When we're back, read TPS and make sure it sill contains the original */
memset(buffer, 0, TPS_SIZE);
tps_read(0, TPS_SIZE, buffer);
assert(!memcmp(msg1, buffer, TPS_SIZE));
printf("thread2: read OK!\n");
/* Transfer CPU to thread 1 and get blocked */
sem_up(sem1);
sem_down(sem2);
/* Destroy TPS and quit */
tps_destroy();
return NULL;
}
void* thread1(void* arg)
{
pthread_t tid;
char *buffer = malloc(TPS_SIZE);
/* Create thread 2 and get blocked */
pthread_create(&tid, NULL, thread2, NULL);
sem_down(sem1);
/* When we're back, clone thread 1's TPS */
tps_clone(tid);
/* Read the TPS and make sure it contains the original */
memset(buffer, 0, TPS_SIZE);
tps_read(0, TPS_SIZE, buffer);
assert(!memcmp(msg1, buffer, TPS_SIZE));
printf("thread1: read OK!\n");
/* Modify TPS to cause a copy on write */
buffer[0] = 'h';
tps_write(0, 1, buffer);
/* Transfer CPU to thread 2 and get blocked */
sem_up(sem2);
sem_down(sem1);
/* When we're back, make sure our modification is still there */
memset(buffer, 0, TPS_SIZE);
tps_read(0, TPS_SIZE, buffer);
assert(!strcmp(msg2, buffer));
printf("thread1: read OK!\n");
/* Transfer CPU to thread 2 */
sem_up(sem2);
/* Wait for thread2 to die, and quit */
pthread_join(tid, NULL);
tps_destroy();
return NULL;
}
int main(int argc, char **argv)
{
pthread_t tid;
/* Create two semaphores for thread synchro */
sem1 = sem_create(0);
sem2 = sem_create(0);
/* Init TPS API */
tps_init(1);
/* Create thread 1 and wait */
pthread_create(&tid, NULL, thread1, NULL);
pthread_join(tid, NULL);
/* Destroy resources and quit */
sem_destroy(sem1);
sem_destroy(sem2);
return 0;
}