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"
19#include "roc_core/attributes.h"
22#include "roc_core/panic.h"
24
25namespace roc {
26namespace core {
27
28class Cond;
29
30//! Mutex.
31class Mutex : public NonCopyable<> {
32public:
33 //! RAII lock.
35
36 //! Initialize mutex.
38
39 //! Destroy mutex.
41
42 //! Try to lock the mutex.
43 ROC_ATTR_NODISCARD inline bool try_lock() const {
44 const int err = pthread_mutex_trylock(&mutex_);
45
46 if (err != 0 && err != EBUSY && err != EAGAIN) {
47 roc_panic("mutex: pthread_mutex_trylock(): %s", errno_to_str(err).c_str());
48 }
49
50 return (err == 0);
51 }
52
53 //! Lock mutex.
54 inline void lock() const {
55 if (int err = pthread_mutex_lock(&mutex_)) {
56 roc_panic("mutex: pthread_mutex_lock(): %s", errno_to_str(err).c_str());
57 }
58 }
59
60 //! Unlock mutex.
61 inline void unlock() const {
62 ++guard_;
63
64 if (int err = pthread_mutex_unlock(&mutex_)) {
65 roc_panic("mutex: pthread_mutex_unlock(): %s", errno_to_str(err).c_str());
66 }
67
68 --guard_;
69 }
70
71private:
72 friend class Cond;
73
74 mutable pthread_mutex_t mutex_;
75 mutable Atomic<int> guard_;
76};
77
78} // namespace core
79} // namespace roc
80
81#endif // ROC_CORE_MUTEX_H_
Atomic.
Compiler attributes.
#define ROC_ATTR_NODISCARD
Emit warning if function result is not checked.
Definition attributes.h:31
Condition variable.
Definition cond.h:28
Mutex()
Initialize mutex.
bool try_lock() const
Try to lock the mutex.
Definition mutex.h:43
ScopedLock< Mutex > Lock
RAII lock.
Definition mutex.h:34
void unlock() const
Unlock mutex.
Definition mutex.h:61
~Mutex()
Destroy mutex.
void lock() const
Lock mutex.
Definition mutex.h:54
Base class for non-copyable objects.
Definition noncopyable.h:23
Shared ownership intrusive pointer.
Definition shared_ptr.h:32
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.