-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample.c
More file actions
37 lines (32 loc) · 755 Bytes
/
example.c
File metadata and controls
37 lines (32 loc) · 755 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
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef enum { PUBLISH, CACHE } ThreadAction;
int global;
int f(ThreadAction action) {
int cache = 0;
switch (action) {
case CACHE:
printf("Store in local cache!\n");
cache = 42;
case PUBLISH:
printf("Publish work!\n");
global = 42;
}
}
void *t(void *arg) {
if (pthread_mutex_trylock(&mutex)) {
f(CACHE);
} else {
f(PUBLISH);
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, t, NULL);
pthread_create(&t2, NULL, t, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}