]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/plr/ex/pthread_mutex/main.c
update
[l4.git] / l4 / pkg / plr / ex / pthread_mutex / main.c
1 #include <stdio.h>
2 #include <assert.h>
3 #include <sys/time.h>
4
5 #include <pthread.h>
6 #include <pthread-l4.h>
7
8 #include <l4/re/env.h>
9 #include <l4/sys/kdebug.h>
10
11
12 static int globalcounter;
13 pthread_mutex_t mtx;
14
15 static const unsigned print_iterations = 100;
16 static const unsigned inc_iterations   = 10000;
17
18 static
19 void *thread(void *data)
20 {
21         (void)data;
22 #if 0
23         while (1) {
24 #else
25         for (unsigned cnt = 0; cnt < print_iterations; ++cnt) {
26 #endif
27                 for (unsigned i = 0; i < inc_iterations; ++i) {
28                         pthread_mutex_lock(&mtx);
29                         globalcounter++;
30                         pthread_mutex_unlock(&mtx);
31                 }
32
33                 pthread_mutex_lock(&mtx);
34                 printf("\033[31mThread: %d\n", globalcounter);
35                 pthread_mutex_unlock(&mtx);
36         }
37         return NULL;
38 }
39
40
41 static int diff_ms(struct timeval *t1, struct timeval *t2)
42 {
43         return (((t1->tv_sec - t2->tv_sec) * 1000000) + 
44                 (t1->tv_usec - t2->tv_usec))/1000;
45 }
46
47
48 int main(int argc, char **argv)
49 {
50         (void)argc; (void)argv;
51
52         pthread_t pt;
53
54         struct timeval start, stop;
55
56         gettimeofday(&start, NULL);
57
58         pthread_mutex_init(&mtx, 0);
59
60         int res = pthread_create(&pt, NULL, thread, NULL);
61         assert(res == 0);
62
63 #if 0
64         while (1) {
65 #else
66         for (unsigned cnt = 0; cnt < print_iterations; ++cnt) {
67 #endif
68                 for (unsigned i = 0; i < inc_iterations; ++i) {
69                         pthread_mutex_lock(&mtx);
70                         globalcounter++;
71                         pthread_mutex_unlock(&mtx);
72                 }
73
74                 pthread_mutex_lock(&mtx);
75                 printf("\033[32mMain: %d\n", globalcounter);
76                 pthread_mutex_unlock(&mtx);
77         }
78
79         pthread_join(pt, NULL);
80
81         gettimeofday(&stop, NULL);
82
83         unsigned long ms = diff_ms(&stop, &start);
84         printf("Start %ld.%ld --- Stop %ld.%ld --- Diff %ld.%03ld\n",
85                start.tv_sec, start.tv_usec, stop.tv_sec, stop.tv_usec,
86                ms / 1000, ms % 1000);
87
88         //enter_kdebug("before return");
89
90         return 0;
91 }