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