Add yaz_thread_{create,join,detach}
[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     YAZ_CHECK(c);
58     if (!c)
59         return;
60
61     r = yaz_gettimeofday(&abstime);
62     YAZ_CHECK_EQ(r, 0);
63     
64     abstime.tv_sec += 1; /* wait 1 second */
65     
66     r = yaz_cond_wait(c, p, &abstime);
67     YAZ_CHECK(r != 0);
68
69     yaz_cond_destroy(&c);
70     YAZ_CHECK(c == 0);
71     yaz_mutex_destroy(&p);
72     YAZ_CHECK(p == 0);
73 }
74
75 static void *my_handler(void *arg)
76 {
77     int *mydata = (int*) arg;
78     (*mydata)++;
79     return mydata;
80 }
81
82 static void tst_create_thread(void)
83 {
84     void *return_data;
85     int mydata = 42;
86     yaz_thread_t t[2];
87
88     t[0] = yaz_thread_create(my_handler, &mydata);
89     YAZ_CHECK(t[0]);
90     t[1] = yaz_thread_create(my_handler, &mydata);
91     YAZ_CHECK(t[1]);
92     
93     return_data = 0;
94     yaz_thread_join(&t[0], &return_data);
95     YAZ_CHECK(!t[0]);
96     YAZ_CHECK(return_data == &mydata);
97
98     return_data = 0;
99     yaz_thread_join(&t[1], &return_data);
100     YAZ_CHECK(!t[1]);
101     YAZ_CHECK(return_data == &mydata);
102     
103     YAZ_CHECK_EQ(mydata, 44);
104 }
105
106 int main (int argc, char **argv)
107 {
108     YAZ_CHECK_INIT(argc, argv);
109     YAZ_CHECK_LOG();
110     tst_mutex();
111     tst_cond();
112     tst_create_thread();
113     YAZ_CHECK_TERM;
114 }
115
116 /*
117  * Local variables:
118  * c-basic-offset: 4
119  * c-file-style: "Stroustrup"
120  * indent-tabs-mode: nil
121  * End:
122  * vim: shiftwidth=4 tabstop=8 expandtab
123  */
124