314fb067f5daa8d5f355075c908e689a02c17f56
[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.5 2006-05-03 09:42:39 marc 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     /* join */
79     WaitForMultipleObjects(NUM_THREADS, handles, TRUE, INFINITE);
80 }
81 #endif
82
83 #if YAZ_POSIX_THREADS
84 static void tst_pthread()
85 {
86     pthread_t child_thread[NUM_THREADS];
87     int i, id[NUM_THREADS];
88     for (i = 0; i<NUM_THREADS; i++)
89         pthread_create(&child_thread[i], 0 /* attr */, run_func, &id[i]);
90
91     for (i = 0; i<NUM_THREADS; i++)
92         pthread_join(child_thread[i], 0);
93 }
94 #endif
95
96 int main(int argc, char **argv)
97 {
98     YAZ_CHECK_INIT(argc, argv);
99
100 #ifdef WIN32
101     tst_win32();
102 #endif
103 #if YAZ_POSIX_THREADS
104     tst_pthread();
105 #endif
106
107     *seqp++ = '\0';
108     printf("seq=%s\n", seq);
109 #if 0
110     /* does not pass.. for bug 529 */
111     YAZ_CHECK(strcmp(seq, "LULULULU") == 0);
112 #endif
113     YAZ_CHECK_TERM;
114 }
115
116