1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
7 * \file compat_mutex_winthreads.c
9 * \brief Implement the tor_mutex API using CRITICAL_SECTION.
14 /* For SRW locks support */
16 #error "orconfig.h didn't define WINVER"
19 #error "orconfig.h didn't define _WIN32_WINNT"
22 #error "winver too low"
24 #if _WIN32_WINNT < 0x0600
25 #error "winver too low"
29 #include "lib/lock/compat_mutex.h"
30 #include "lib/err/torerr.h"
33 tor_locking_init(void)
38 tor_mutex_init(tor_mutex_t
*m
)
43 InitializeSRWLock(&m
->mutex
);
46 tor_mutex_init_nonrecursive(tor_mutex_t
*m
)
48 m
->type
= NON_RECURSIVE
;
49 InitializeSRWLock(&m
->mutex
);
53 tor_mutex_uninit(tor_mutex_t
*m
)
59 tor_mutex_acquire_recursive(tor_mutex_t
*m
)
61 LONG thread_id
= GetCurrentThreadId();
62 // use InterlockedCompareExchange to perform an atomic read
63 LONG lock_owner
= InterlockedCompareExchange(&m
->lock_owner
, 0, 0);
64 if (thread_id
== lock_owner
) {
68 AcquireSRWLockExclusive(&m
->mutex
);
69 InterlockedExchange(&m
->lock_owner
, thread_id
);
74 tor_mutex_acquire_nonrecursive(tor_mutex_t
*m
)
76 AcquireSRWLockExclusive(&m
->mutex
);
80 tor_mutex_acquire(tor_mutex_t
*m
)
83 if (m
->type
== NON_RECURSIVE
) {
84 tor_mutex_acquire_nonrecursive(m
);
86 tor_mutex_acquire_recursive(m
);
91 tor_mutex_release_recursive(tor_mutex_t
*m
)
93 if (--m
->lock_count
) {
96 InterlockedExchange(&m
->lock_owner
, 0);
97 ReleaseSRWLockExclusive(&m
->mutex
);
101 tor_mutex_release_nonrecursive(tor_mutex_t
*m
)
103 ReleaseSRWLockExclusive(&m
->mutex
);
107 tor_mutex_release(tor_mutex_t
*m
)
109 if (m
->type
== NON_RECURSIVE
) {
110 tor_mutex_release_nonrecursive(m
);
112 tor_mutex_release_recursive(m
);