tor  0.4.1.0-alpha-dev
compat_mutex_pthreads.c
Go to the documentation of this file.
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 */
5 
12 #include "lib/lock/compat_mutex.h"
13 #include "lib/cc/compat_compiler.h"
14 #include "lib/err/torerr.h"
15 
19 static pthread_mutexattr_t attr_recursive;
20 static int attr_initialized = 0;
21 
22 void
23 tor_locking_init(void)
24 {
25  if (!attr_initialized) {
26  pthread_mutexattr_init(&attr_recursive);
27  pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE);
28  attr_initialized = 1;
29  }
30 }
31 
34 void
36 {
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
44  }
45 }
46 
49 void
51 {
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
60  }
61 }
62 
64 void
66 {
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
74  }
75 }
77 void
79 {
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
87  }
88 }
92 void
94 {
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
102  }
103 }
static pthread_mutexattr_t attr_recursive
void tor_mutex_uninit(tor_mutex_t *m)
void tor_mutex_release(tor_mutex_t *m)
Utility macros to handle different features and behavior in different compilers.
void tor_mutex_init(tor_mutex_t *mutex)
void tor_mutex_acquire(tor_mutex_t *m)
void tor_mutex_init_nonrecursive(tor_mutex_t *mutex)
Header for compat_mutex.c.
Headers for torerr.c.