Refactor tests for WIN32/pthread
[idzebra-moved-to-github.git] / util / tstflock.c
1 /*
2  * Copyright (C) 1995-2005, Index Data ApS
3  * See the file LICENSE for details.
4  *
5  * $Id: tstflock.c,v 1.3 2006-03-23 17:32:03 adam Exp $
6  */
7
8 #include <yaz/test.h>
9 #if YAZ_POSIX_THREADS
10 #include <pthread.h>
11 #endif
12 #ifdef WIN32
13 #include <windows.h>
14 #include <process.h>
15 #endif
16
17 #include <idzebra/flock.h>
18 #if HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #include <string.h>
22
23 static char seq[20];
24 static char *seqp = seq;
25
26 #define NUM_THREADS 2
27
28 static void small_sleep()
29 {
30 #ifdef WIN32
31     Sleep(50);
32 #else
33     sleep(1);
34 #endif
35 }
36 void *run_func(void *arg)
37 {
38     int i;
39     ZebraLockHandle lh = zebra_lock_create(0, "my.LCK");
40     for (i = 0; i<2; i++)
41     {
42         zebra_lock_w(lh);
43      
44         *seqp++ = 'L';
45         small_sleep();
46         *seqp++ = 'U';
47         
48         zebra_unlock(lh);
49     }
50     zebra_lock_destroy(lh);
51     return 0;
52 }
53
54 #ifdef WIN32
55 DWORD WINAPI ThreadProc(void *p)
56 {
57     run_func(p);
58     return 0;
59 }
60
61 static void tst_win32()
62 {
63     HANDLE handles[NUM_THREADS];
64     DWORD dwThreadId[NUM_THREADS];
65     int i, id[NUM_THREADS];
66     
67     for (i = 0; i<NUM_THREADS; i++)
68     {
69         void *pData = &id[i];
70         handles[i] = CreateThread(
71             NULL,              /* default security attributes */
72             0,                 /* use default stack size */
73             ThreadProc,        /* thread function */
74             pData,             /* argument to thread function */
75             0,                 /* use default creation flags */
76             &dwThreadId[i]);   /* returns the thread identifier */
77     }
78     WaitForMultipleObjects(NUM_THREADS, handles, TRUE, INFINITE);
79     /* join */
80     *seqp++ = '\0';
81 }
82 #endif
83
84 #if YAZ_POSIX_THREADS
85 static void tst_pthread()
86 {
87     pthread_t child_thread[NUM_THREADS];
88     int i, id[NUM_THREADS];
89     for (i = 0; i<NUM_THREADS; i++)
90         pthread_create(&child_thread[i], 0 /* attr */, run_func, &id[i]);
91
92     for (i = 0; i<NUM_THREADS; i++)
93         pthread_join(child_thread[i], 0);
94     *seqp++ = '\0';
95 }
96 #endif
97
98 int main(int argc, char **argv)
99 {
100     YAZ_CHECK_INIT(argc, argv);
101
102 #ifdef WIN32
103     tst_win32();
104 #endif
105 #if YAZ_POSIX_THREADS
106     tst_pthread();
107 #endif
108
109     *seqp++ = '\0';
110     printf("seq=%s\n", seq);
111 #if 0
112     /* does not pass.. for bug 529 */
113     YAZ_CHECK(strcmp(seq, "LULULULU") == 0);
114 #endif
115     YAZ_CHECK_TERM;
116 }
117 /*
118  * Local variables:
119  * c-basic-offset: 4
120  * indent-tabs-mode: nil
121  * End:
122  * vim: shiftwidth=4 tabstop=8 expandtab
123  */
124