Allow passing in human-readable units for specifying amounts of space
[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
14 #if defined(AFS_NT40_ENV) && defined(AFS_PTHREAD_ENV)
15 #define AFS_GRMUTEX_DECLSPEC __declspec(dllexport)
16 #endif
17 #include <afs/pthread_glock.h>
18 #include <string.h>
19
20 /*
21  * Implement a pthread based recursive global lock for use in porting
22  * old lwp style code to pthreads.
23  */
24
25 pthread_recursive_mutex_t grmutex;
26
27 static int glock_init = 0;
28 static pthread_once_t glock_init_once = PTHREAD_ONCE_INIT;
29
30 static void
31 glock_init_func(void)
32 {
33     pthread_mutex_init(&grmutex.mut, (const pthread_mutexattr_t *)0);
34     grmutex.times_inside = 0;
35     grmutex.owner = (pthread_t) 0;
36     grmutex.locked = 0;
37     glock_init = 1;
38 }
39
40 int
41 pthread_recursive_mutex_lock(pthread_recursive_mutex_t * mut)
42 {
43     int rc = 0;
44
45     (glock_init || pthread_once(&glock_init_once, glock_init_func));
46
47     if (mut->locked) {
48         if (pthread_equal(mut->owner, pthread_self())) {
49             mut->times_inside++;
50             return rc;
51         }
52     }
53     rc = pthread_mutex_lock(&mut->mut);
54     if (rc == 0) {
55         mut->times_inside = 1;
56         mut->owner = pthread_self();
57         mut->locked = 1;
58     }
59
60     return rc;
61 }
62
63 int
64 pthread_recursive_mutex_unlock(pthread_recursive_mutex_t * mut)
65 {
66     int rc = 0;
67
68     (glock_init || pthread_once(&glock_init_once, glock_init_func));
69
70     if ((mut->locked) && (pthread_equal(mut->owner, pthread_self()))) {
71         mut->times_inside--;
72         if (mut->times_inside == 0) {
73             mut->locked = 0;
74             rc = pthread_mutex_unlock(&mut->mut);
75         }
76     } else {
77         /*
78          * Note that you might want to try to differentiate between
79          * the two possible reasons you're here, but since we don't
80          * hold the mutex, it's useless to try.
81          */
82         rc = -1;
83     }
84     return rc;
85 }