Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
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"
20 #include "roc_core/errno_to_str.h"
21 #include "roc_core/noncopyable.h"
22 #include "roc_core/panic.h"
23 #include "roc_core/scoped_lock.h"
24 
25 namespace roc {
26 namespace core {
27 
28 class Cond;
29 
30 //! Mutex.
31 class Mutex : public NonCopyable<> {
32 public:
33  //! RAII lock.
35 
36  //! Initialize mutex.
37  Mutex();
38 
39  //! Destroy mutex.
40  ~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 
71 private:
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.
Definition: mutex.h:31
Mutex()
Initialize mutex.
ScopedLock< Mutex > Lock
RAII lock.
Definition: mutex.h:34
void unlock() const
Unlock mutex.
Definition: mutex.h:61
~Mutex()
Destroy mutex.
ROC_ATTR_NODISCARD bool try_lock() const
Try to lock the mutex.
Definition: mutex.h:43
void lock() const
Lock mutex.
Definition: mutex.h:54
Base class for non-copyable objects.
Definition: noncopyable.h:23
RAII mutex lock.
Definition: scoped_lock.h:21
Convert errno to string.
Definition: errno_to_str.h:23
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.