Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
Loading...
Searching...
No Matches
mutex.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2015 Roc Streaming authors
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 */
8
9//! @file roc_core/target_posix/roc_core/mutex.h
10//! @brief Mutex.
11
12#ifndef ROC_CORE_MUTEX_H_
13#define ROC_CORE_MUTEX_H_
14
15#include <errno.h>
16#include <pthread.h>
17
18#include "roc_core/atomic.h"
21#include "roc_core/panic.h"
23
24namespace roc {
25namespace core {
26
27class Cond;
28
29//! Mutex.
30class Mutex : public NonCopyable<> {
31public:
32 //! RAII lock.
34
35 //! Initialize mutex.
37
38 //! Destroy mutex.
40
41 //! Try to lock the mutex.
42 inline bool try_lock() const {
43 const int err = pthread_mutex_trylock(&mutex_);
44
45 if (err != 0 && err != EBUSY && err != EAGAIN) {
46 roc_panic("mutex: pthread_mutex_trylock(): %s", errno_to_str(err).c_str());
47 }
48
49 return (err == 0);
50 }
51
52 //! Lock mutex.
53 inline void lock() const {
54 if (int err = pthread_mutex_lock(&mutex_)) {
55 roc_panic("mutex: pthread_mutex_lock(): %s", errno_to_str(err).c_str());
56 }
57 }
58
59 //! Unlock mutex.
60 inline void unlock() const {
61 ++guard_;
62
63 if (int err = pthread_mutex_unlock(&mutex_)) {
64 roc_panic("mutex: pthread_mutex_unlock(): %s", errno_to_str(err).c_str());
65 }
66
67 --guard_;
68 }
69
70private:
71 friend class Cond;
72
73 mutable pthread_mutex_t mutex_;
74 mutable Atomic<int> guard_;
75};
76
77} // namespace core
78} // namespace roc
79
80#endif // ROC_CORE_MUTEX_H_
Atomic.
Atomic integer. Provides sequential consistency. For a fine-grained memory order control,...
Definition atomic.h:26
Condition variable.
Definition cond.h:27
Mutex()
Initialize mutex.
bool try_lock() const
Try to lock the mutex.
Definition mutex.h:42
ScopedLock< Mutex > Lock
RAII lock.
Definition mutex.h:33
void unlock() const
Unlock mutex.
Definition mutex.h:60
~Mutex()
Destroy mutex.
void lock() const
Lock mutex.
Definition mutex.h:53
Base class for non-copyable objects.
Definition noncopyable.h:23
RAII mutex lock.
Definition scoped_lock.h:21
Convert errno to string.
Convert errno to string.
Root namespace.
Non-copyable object.
Panic.
#define roc_panic(...)
Print error message and terminate program gracefully.
Definition panic.h:50
RAII mutex lock.