Remove unused function: dns_randfn_() in dns.c.
[tor.git] / src / lib / lock / compat_mutex_pthreads.c
blobee5f520cd04dc9daf0f13b4498110de1ceab0141
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 */
6 /**
7 * \file compat_mutex_pthreads.c
9 * \brief Implement the tor_mutex API using pthread_mutex_t.
10 **/
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
18 * them.) */
19 static pthread_mutexattr_t attr_recursive;
20 static int attr_initialized = 0;
22 void
23 tor_locking_init(void)
25 if (!attr_initialized) {
26 pthread_mutexattr_init(&attr_recursive);
27 pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
28 attr_initialized = 1;
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. */
34 void
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)) {
41 // LCOV_EXCL_START
42 raw_assert_unreached_msg("Error creating a mutex.");
43 // LCOV_EXCL_STOP
47 /** As tor_mutex_init, but initialize a mutex suitable that may be
48 * non-recursive, if the OS supports that. */
49 void
50 tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
52 int err;
53 if (!attr_initialized)
54 tor_locking_init(); // LCOV_EXCL_LINE
55 err = pthread_mutex_init(&mutex->mutex, NULL);
56 if (PREDICT_UNLIKELY(err)) {
57 // LCOV_EXCL_START
58 raw_assert_unreached_msg("Error creating a mutex.");
59 // LCOV_EXCL_STOP
63 /** Wait until <b>m</b> is free, then acquire it. */
64 void
65 tor_mutex_acquire(tor_mutex_t *m)
67 int err;
68 raw_assert(m);
69 err = pthread_mutex_lock(&m->mutex);
70 if (PREDICT_UNLIKELY(err)) {
71 // LCOV_EXCL_START
72 raw_assert_unreached_msg("Error locking a mutex.");
73 // LCOV_EXCL_STOP
76 /** Release the lock <b>m</b> so another thread can have it. */
77 void
78 tor_mutex_release(tor_mutex_t *m)
80 int err;
81 raw_assert(m);
82 err = pthread_mutex_unlock(&m->mutex);
83 if (PREDICT_UNLIKELY(err)) {
84 // LCOV_EXCL_START
85 raw_assert_unreached_msg("Error unlocking a mutex.");
86 // LCOV_EXCL_STOP
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(). */
92 void
93 tor_mutex_uninit(tor_mutex_t *m)
95 int err;
96 raw_assert(m);
97 err = pthread_mutex_destroy(&m->mutex);
98 if (PREDICT_UNLIKELY(err)) {
99 // LCOV_EXCL_START
100 raw_assert_unreached_msg("Error destroying a mutex.");
101 // LCOV_EXCL_STOP