reindent-20030715
[openafs.git] / src / util / pthread_glock.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #if defined(AFS_NT40_ENV) && defined(AFS_PTHREAD_ENV)
17 #define AFS_GRMUTEX_DECLSPEC __declspec(dllexport)
18 #endif
19 #include <afs/pthread_glock.h>
20 #include <string.h>
21
22 /*
23  * Implement a pthread based recursive global lock for use in porting
24  * old lwp style code to pthreads.
25  */
26
27 pthread_recursive_mutex_t grmutex;
28
29 static int glock_init;
30 static pthread_once_t glock_init_once = PTHREAD_ONCE_INIT;
31
32 static void
33 glock_init_func(void)
34 {
35     pthread_mutex_init(&grmutex.mut, (const pthread_mutexattr_t *)0);
36     grmutex.times_inside = 0;
37     grmutex.owner = (pthread_t) 0;
38     grmutex.locked = 0;
39     glock_init = 1;
40 }
41
42 int
43 pthread_recursive_mutex_lock(pthread_recursive_mutex_t * mut)
44 {
45     int rc = 0;
46
47     (glock_init || pthread_once(&glock_init_once, glock_init_func));
48
49     if (mut->locked) {
50         if (pthread_equal(mut->owner, pthread_self())) {
51             mut->times_inside++;
52             return rc;
53         }
54     }
55     rc = pthread_mutex_lock(&mut->mut);
56     if (rc == 0) {
57         mut->times_inside = 1;
58         mut->owner = pthread_self();
59         mut->locked = 1;
60     }
61
62     return rc;
63 }
64
65 int
66 pthread_recursive_mutex_unlock(pthread_recursive_mutex_t * mut)
67 {
68     int rc = 0;
69
70     (glock_init || pthread_once(&glock_init_once, glock_init_func));
71
72     if ((mut->locked) && (pthread_equal(mut->owner, pthread_self()))) {
73         mut->times_inside--;
74         if (mut->times_inside == 0) {
75             mut->locked = 0;
76             rc = pthread_mutex_unlock(&mut->mut);
77         }
78     } else {
79         /*
80          * Note that you might want to try to differentiate between
81          * the two possible reasons you're here, but since we don't
82          * hold the mutex, it's useless to try.
83          */
84         rc = -1;
85     }
86     return rc;
87 }