Add two more tests with anchoring
[yaz-moved-to-github.git] / test / test_mutex.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) 1995-2012 Index Data
3  * See the file LICENSE for details.
4  */
5 #if HAVE_CONFIG_H
6 #include <config.h>
7 #endif
8
9 #include <stdlib.h>
10 #include <stdio.h>
11
12 #include <yaz/mutex.h>
13 #include <yaz/thread_create.h>
14 #if HAVE_SYS_TIME_H
15 #include <sys/time.h>
16 #endif
17 #ifdef WIN32
18 #include <windows.h>
19 #endif
20
21 #include <yaz/test.h>
22 #include <yaz/log.h>
23 #include <yaz/gettimeofday.h>
24
25 static void tst_mutex(void)
26 {
27     YAZ_MUTEX p = 0;
28
29     yaz_mutex_create(&p);
30     YAZ_CHECK(p);
31     yaz_mutex_enter(p);
32     yaz_mutex_leave(p);
33     yaz_mutex_destroy(&p);
34     YAZ_CHECK(p == 0);
35
36     yaz_mutex_create(&p);
37     YAZ_CHECK(p);
38     yaz_mutex_set_name(p, YLOG_LOG, "mymutex");
39     yaz_mutex_enter(p);
40     yaz_mutex_leave(p);
41     yaz_mutex_destroy(&p);
42     YAZ_CHECK(p == 0);
43
44     yaz_mutex_destroy(&p); /* OK to "destroy" NULL handle */
45 }
46
47 static void tst_cond(void)
48 {
49     YAZ_MUTEX p = 0;
50     YAZ_COND c;
51     struct timeval abstime;
52     int r;
53
54     yaz_mutex_create(&p);
55     YAZ_CHECK(p);
56     if (!p)
57         return;
58
59     yaz_cond_create(&c);
60     if (c)
61     {
62         r = yaz_gettimeofday(&abstime);
63         YAZ_CHECK_EQ(r, 0);
64
65         abstime.tv_sec += 1; /* wait 1 second */
66
67         r = yaz_cond_wait(c, p, &abstime);
68         YAZ_CHECK(r != 0);
69
70     }
71     yaz_cond_destroy(&c);
72     YAZ_CHECK(c == 0);
73     yaz_mutex_destroy(&p);
74     YAZ_CHECK(p == 0);
75 }
76
77 static void *my_handler(void *arg)
78 {
79     int *mydata = (int*) arg;
80     (*mydata)++;
81     return mydata;
82 }
83
84 static void tst_create_thread(void)
85 {
86     void *return_data;
87     int mydata = 42;
88     yaz_thread_t t[2];
89
90     t[0] = yaz_thread_create(my_handler, &mydata);
91     YAZ_CHECK(t[0]);
92     t[1] = yaz_thread_create(my_handler, &mydata);
93     YAZ_CHECK(t[1]);
94
95     return_data = 0;
96     yaz_thread_join(&t[0], &return_data);
97     YAZ_CHECK(!t[0]);
98     YAZ_CHECK(return_data == &mydata);
99
100     return_data = 0;
101     yaz_thread_join(&t[1], &return_data);
102     YAZ_CHECK(!t[1]);
103     YAZ_CHECK(return_data == &mydata);
104
105     YAZ_CHECK_EQ(mydata, 44);
106 }
107
108 int main (int argc, char **argv)
109 {
110     YAZ_CHECK_INIT(argc, argv);
111     YAZ_CHECK_LOG();
112     tst_mutex();
113     tst_cond();
114     tst_create_thread();
115     YAZ_CHECK_TERM;
116 }
117
118 /*
119  * Local variables:
120  * c-basic-offset: 4
121  * c-file-style: "Stroustrup"
122  * indent-tabs-mode: nil
123  * End:
124  * vim: shiftwidth=4 tabstop=8 expandtab
125  */
126