-
Notifications
You must be signed in to change notification settings - Fork 294
/
blocky.c
69 lines (57 loc) · 1.37 KB
/
blocky.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
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
volatile long work_counter;
int req_count;
pthread_mutex_t q_lock;
void grab_lock() {
pthread_mutex_lock(&q_lock);
}
void ungrab_lock() {
pthread_mutex_unlock(&q_lock);
}
void do_work() {
for (int i = 0; i < 50000; ++i)
++work_counter; // Burn CPU
}
void * request_processor(void *dummy) {
printf("[*] Request processor initialized.\n");
while (1) {
grab_lock();
do_work();
ungrab_lock();
}
return NULL;
}
void flush_work() {
usleep(10000); // 10ms
}
void * backend_handler(void *dummy) {
printf("[*] Backend handler initialized.\n");
while (1) {
grab_lock();
++req_count;
if (req_count % 1000 == 0) {
printf("[-] Handled %d requests.\n", req_count);
}
if (req_count % 37 == 0) {
flush_work();
}
ungrab_lock();
}
return NULL;
}
#define NTHREADS 2
int main() {
pthread_t req_processors[NTHREADS];
pthread_t backend;
pthread_mutex_init(&q_lock, NULL);
for (int i = 0; i < NTHREADS; ++i) {
pthread_create(&req_processors[i], NULL, request_processor, NULL);
}
pthread_create(&backend, NULL, backend_handler, NULL);
printf("[*] Ready to process requests.\n");
pthread_join(backend, NULL);
printf("[*] Exiting.\n");
return 0;
}