Debian Codegraph @

libs/xpdf/xpdf-src/goo/GMutex.h

raw
1 //========================================================================
2 //
3 // GMutex.h
4 //
5 // Portable mutex macros.
6 // Portable atomic increment/decrement.
7 //
8 // Copyright 2002-2014 Glyph & Cog, LLC
9 //
10 //========================================================================
11
12 #ifndef GMUTEX_H
13 #define GMUTEX_H
14
15 #include <aconf.h>
16 #ifdef _WIN32
17 # include <windows.h>
18 # include <intrin.h>
19 #else
20 # include <pthread.h>
21 #endif
22
23 //------------------------------------------------------------------------
24 // GMutex
25 //------------------------------------------------------------------------
26
27 // Usage:
28 //
29 // GMutex m;
30 // gInitMutex(&m);
31 // ...
32 // gLockMutex(&m);
33 // ... critical section ...
34 // gUnlockMutex(&m);
35 // ...
36 // gDestroyMutex(&m);
37
38 #ifdef _WIN32
39
40 typedef CRITICAL_SECTION GMutex;
41
42 #define gInitMutex(m) InitializeCriticalSection(m)
43 #define gDestroyMutex(m) DeleteCriticalSection(m)
44 #define gLockMutex(m) EnterCriticalSection(m)
45 #define gUnlockMutex(m) LeaveCriticalSection(m)
46
47 #else // assume pthreads
48
49 typedef pthread_mutex_t GMutex;
50
51 #define gInitMutex(m) pthread_mutex_init(m, NULL)
52 #define gDestroyMutex(m) pthread_mutex_destroy(m)
53 #define gLockMutex(m) pthread_mutex_lock(m)
54 #define gUnlockMutex(m) pthread_mutex_unlock(m)
55
56 #endif
57
58 //------------------------------------------------------------------------
59 // atomic increment/decrement
60 //------------------------------------------------------------------------
61
62 // NB: this must be "long" to work on Windows
63 typedef long GAtomicCounter;
64
65 // Increment *counter by one and return the final value (after the
66 // increment).
67 static inline GAtomicCounter gAtomicIncrement(GAtomicCounter *counter) {
68 GAtomicCounter newVal;
69
70 #if defined(_WIN32)
71 newVal = _InterlockedIncrement(counter);
72 #elif defined(__GNUC__) || defined(__xlC__)
73 // __GNUC__ also covers LLVM/clang
74 newVal = __sync_add_and_fetch(counter, 1);
75 #elif defined(__SUNPRO_CC)
76 newVal = atomic_inc_ulong_nv((ulong_t *)counter);
77 #else
78 # error "gAtomicIncrement is not defined for this compiler/platform"
79 #endif
80 return newVal;
81 }
82
83 // Decrement *counter by one and return the final value (after the
84 // decrement).
85 static inline GAtomicCounter gAtomicDecrement(GAtomicCounter *counter) {
86 GAtomicCounter newVal;
87
88 #if defined(_WIN32)
89 newVal = _InterlockedDecrement(counter);
90 #elif defined(__GNUC__) || defined(__xlC__)
91 // __GNUC__ also covers LLVM/clang
92 newVal = __sync_sub_and_fetch(counter, 1);
93 #elif defined(__SUNPRO_CC)
94 newVal = atomic_dec_ulong_nv((ulong_t *)counter);
95 #else
96 # error "gAtomicDecrement is not defined for this compiler/platform"
97 #endif
98 return newVal;
99 }
100
101 #endif // GMUTEX_H