Ticket #6130: cvt1.c

File cvt1.c, 1.0 KB (added by Gennady Proskurin <gpr@…>, 11 years ago)
Line 
1#include <pthread.h>
2#include <assert.h>
3#include <stdlib.h>
4#include <unistd.h>
5#include <errno.h>
6#include <stdio.h>
7
8pthread_mutex_t mtx;
9pthread_cond_t cv;
10
11void mutex_lock()
12{
13 if (pthread_mutex_lock(&mtx) != 0)
14 _exit(3);
15}
16
17void mutex_unlock()
18{
19 if (pthread_mutex_unlock(&mtx) != 0)
20 _exit(3);
21}
22
23int main()
24{
25 if (0 != pthread_mutex_init(&mtx,0))
26 return 1;
27 if (0 != pthread_cond_init(&cv,0))
28 return 2;
29
30 while(1) {
31 int i;
32 for (i=0; i<3; ++i) {
33 mutex_lock();
34 const time_t wait_time = time(0)+1;
35 struct timespec tm;
36 tm.tv_sec = wait_time;
37 tm.tv_nsec = 0;
38 const int err = pthread_cond_timedwait(&cv, &mtx, &tm);
39 if (err != ETIMEDOUT) {
40 printf("error cond\n");
41 return 4;
42 }
43 const time_t end_time = time(0);
44 mutex_unlock();
45 if (end_time < wait_time) {
46 printf("wait:%lu wakeup:%lu\n", (long)wait_time, (long)end_time);
47 assert(!"early wakeup");
48 }
49 printf("OK\n");
50 }
51 const long s = random() % 100000;
52 printf("switch, sleep %l ms\n", s);
53 usleep(s);
54 }
55}