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