Rizin
unix-like reverse engineering framework and cli tools
thread_lock.c
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: 2009-2017 pancake <pancake@nopcode.org>
2 // SPDX-FileCopyrightText: 2022 deroad <wargio@libero.it>
3 // SPDX-License-Identifier: LGPL-3.0-only
4 
5 #include "thread.h"
6 
16  if (!thl) {
17  return NULL;
18  }
19 #if HAVE_PTHREAD
20  if (recursive) {
21  pthread_mutexattr_t attr;
22  pthread_mutexattr_init(&attr);
23 #if !defined(__GLIBC__) || __USE_UNIX98__
24  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
25 #else
26  pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
27 #endif
28  pthread_mutex_init(&thl->lock, &attr);
29  } else {
30  pthread_mutex_init(&thl->lock, NULL);
31  }
32 #elif __WINDOWS__
33  // Windows critical sections always accept recursive
34  // access and it cannot be configured in any other way.
35  InitializeCriticalSection(&thl->lock);
36 #endif
37  return thl;
38 }
39 
46  rz_return_if_fail(thl);
47 #if HAVE_PTHREAD
48  pthread_mutex_lock(&thl->lock);
49 #elif __WINDOWS__
50  EnterCriticalSection(&thl->lock);
51 #endif
52 }
53 
62  rz_return_val_if_fail(thl, false);
63 #if HAVE_PTHREAD
64  return !pthread_mutex_trylock(&thl->lock);
65 #elif __WINDOWS__
66  return TryEnterCriticalSection(&thl->lock);
67 #endif
68 }
69 
76  rz_return_if_fail(thl);
77 #if HAVE_PTHREAD
78  pthread_mutex_unlock(&thl->lock);
79 #elif __WINDOWS__
80  LeaveCriticalSection(&thl->lock);
81 #endif
82 }
83 
90  if (!thl) {
91  return;
92  }
93 #if HAVE_PTHREAD
94  pthread_mutex_destroy(&thl->lock);
95 #elif __WINDOWS__
96  DeleteCriticalSection(&thl->lock);
97 #endif
98  free(thl);
99 }
#define RZ_API
#define NULL
Definition: cris-opc.c:27
RZ_API void Ht_() free(HtName_(Ht) *ht)
Definition: ht_inc.c:130
#define rz_return_if_fail(expr)
Definition: rz_assert.h:100
#define rz_return_val_if_fail(expr, val)
Definition: rz_assert.h:108
#define RZ_NULLABLE
Definition: rz_types.h:65
#define RZ_OWN
Definition: rz_types.h:62
#define RZ_NEW0(x)
Definition: rz_types.h:284
#define RZ_NONNULL
Definition: rz_types.h:64
RZ_TH_LOCK_T lock
Definition: thread.h:77
RZ_API void rz_th_lock_leave(RZ_NONNULL RzThreadLock *thl)
Releases a RzThreadLock structure.
Definition: thread_lock.c:75
RZ_API void rz_th_lock_free(RZ_NULLABLE RzThreadLock *thl)
Frees a RzThreadLock structure.
Definition: thread_lock.c:89
RZ_API RZ_OWN RzThreadLock * rz_th_lock_new(bool recursive)
Allocates and initialize a RzThreadLock structure.
Definition: thread_lock.c:14
RZ_API bool rz_th_lock_tryenter(RZ_NONNULL RzThreadLock *thl)
Tries to acquire a RzThreadLock structure.
Definition: thread_lock.c:61
RZ_API void rz_th_lock_enter(RZ_NONNULL RzThreadLock *thl)
Acquires a RzThreadLock structure.
Definition: thread_lock.c:45