1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
7 * \file compat_mutex_pthreads.c
9 * \brief Implement the tor_mutex API using pthread_mutex_t.
12 #include "lib/lock/compat_mutex.h"
13 #include "lib/cc/compat_compiler.h"
14 #include "lib/err/torerr.h"
16 /** A mutex attribute that we're going to use to tell pthreads that we want
17 * "recursive" mutexes (i.e., once we can re-lock if we're already holding
19 static pthread_mutexattr_t attr_recursive
;
20 static int attr_initialized
= 0;
23 tor_locking_init(void)
25 if (!attr_initialized
) {
26 pthread_mutexattr_init(&attr_recursive
);
27 pthread_mutexattr_settype(&attr_recursive
, PTHREAD_MUTEX_RECURSIVE
);
32 /** Initialize <b>mutex</b> so it can be locked. Every mutex must be set
33 * up with tor_mutex_init() or tor_mutex_new(); not both. */
35 tor_mutex_init(tor_mutex_t
*mutex
)
37 if (PREDICT_UNLIKELY(!attr_initialized
))
38 tor_locking_init(); // LCOV_EXCL_LINE
39 const int err
= pthread_mutex_init(&mutex
->mutex
, &attr_recursive
);
40 if (PREDICT_UNLIKELY(err
)) {
42 raw_assert_unreached_msg("Error creating a mutex.");
47 /** As tor_mutex_init, but initialize a mutex suitable that may be
48 * non-recursive, if the OS supports that. */
50 tor_mutex_init_nonrecursive(tor_mutex_t
*mutex
)
53 if (!attr_initialized
)
54 tor_locking_init(); // LCOV_EXCL_LINE
55 err
= pthread_mutex_init(&mutex
->mutex
, NULL
);
56 if (PREDICT_UNLIKELY(err
)) {
58 raw_assert_unreached_msg("Error creating a mutex.");
63 /** Wait until <b>m</b> is free, then acquire it. */
65 tor_mutex_acquire(tor_mutex_t
*m
)
69 err
= pthread_mutex_lock(&m
->mutex
);
70 if (PREDICT_UNLIKELY(err
)) {
72 raw_assert_unreached_msg("Error locking a mutex.");
76 /** Release the lock <b>m</b> so another thread can have it. */
78 tor_mutex_release(tor_mutex_t
*m
)
82 err
= pthread_mutex_unlock(&m
->mutex
);
83 if (PREDICT_UNLIKELY(err
)) {
85 raw_assert_unreached_msg("Error unlocking a mutex.");
89 /** Clean up the mutex <b>m</b> so that it no longer uses any system
90 * resources. Does not free <b>m</b>. This function must only be called on
91 * mutexes from tor_mutex_init(). */
93 tor_mutex_uninit(tor_mutex_t
*m
)
97 err
= pthread_mutex_destroy(&m
->mutex
);
98 if (PREDICT_UNLIKELY(err
)) {
100 raw_assert_unreached_msg("Error destroying a mutex.");