1//
2// Mutex_STD.h
3//
4// Library: Foundation
5// Package: Threading
6// Module: Mutex
7//
8// Definition of the MutexImpl and FastMutexImpl classes for std::mutex.
9//
10// Copyright (c) 2004-2008, Applied Informatics Software Engineering GmbH.
11// and Contributors.
12//
13// SPDX-License-Identifier: BSL-1.0
14//
15
16
17#ifndef Foundation_Mutex_STD_INCLUDED
18#define Foundation_Mutex_STD_INCLUDED
19
20
21#include "Poco/Foundation.h"
22#include "Poco/Exception.h"
23#include <mutex>
24#include <chrono>
25#include <memory>
26
27
28namespace Poco {
29
30
31class Foundation_API MutexImpl_BaseMutex
32 // Helper class to make std::recursive_timed_mutex and std::timed_mutex generic
33{
34public:
35 virtual ~MutexImpl_BaseMutex() {}
36
37 virtual void lock() = 0;
38 virtual bool tryLock() = 0;
39 virtual bool tryLock(long milliseconds) = 0;
40 virtual void unlock() = 0;
41};
42
43
44template <class T>
45class MutexImpl_MutexI : public MutexImpl_BaseMutex
46{
47public:
48 MutexImpl_MutexI() : _mutex() {}
49
50 void lock()
51 {
52 _mutex.lock();
53 }
54
55 bool tryLock()
56 {
57 return _mutex.try_lock();
58 }
59
60 bool tryLock(long milliseconds)
61 {
62 return _mutex.try_lock_for(std::chrono::milliseconds(milliseconds));
63 }
64
65 void unlock()
66 {
67 _mutex.unlock();
68 }
69private:
70 T _mutex;
71};
72
73
74class Foundation_API MutexImpl
75{
76public:
77 enum MutexTypeImpl
78 {
79 MUTEX_RECURSIVE_IMPL,
80 MUTEX_NONRECURSIVE_IMPL,
81 };
82
83 MutexImpl(const MutexImpl&) = delete;
84 MutexImpl& operator = (const MutexImpl&) = delete;
85
86protected:
87 explicit MutexImpl(MutexTypeImpl type);
88 void lockImpl();
89 bool tryLockImpl();
90 bool tryLockImpl(long milliseconds);
91 void unlockImpl();
92
93private:
94 std::unique_ptr<MutexImpl_BaseMutex> _mutex;
95};
96
97
98class Foundation_API FastMutexImpl
99{
100protected:
101 FastMutexImpl();
102 void lockImpl();
103 bool tryLockImpl();
104 bool tryLockImpl(long milliseconds);
105 void unlockImpl();
106
107private:
108 std::timed_mutex _mutex;
109};
110
111
112//
113// inlines
114//
115inline void MutexImpl::lockImpl()
116{
117 _mutex->lock();
118}
119
120inline bool MutexImpl::tryLockImpl()
121{
122 return _mutex->tryLock();
123}
124
125inline void MutexImpl::unlockImpl()
126{
127 _mutex->unlock();
128}
129
130inline void FastMutexImpl::lockImpl()
131{
132 _mutex.lock();
133}
134
135inline bool FastMutexImpl::tryLockImpl()
136{
137 return _mutex.try_lock();
138}
139
140inline void FastMutexImpl::unlockImpl()
141{
142 _mutex.unlock();
143}
144
145
146} // namespace Poco
147
148
149#endif // Foundation_Mutex_STD_INCLUDED
150