TTKMusicPlayer  4.3.0.0
TTKMusicPlayer imitates Kugou UI, the music player uses of qmmp core library based on Qt for windows and linux
ttkspinlock.h
Go to the documentation of this file.
1 #ifndef TTKSPINLOCK_H
2 #define TTKSPINLOCK_H
3 
4 /***************************************************************************
5  * This file is part of the TTK Library Module project
6  * Copyright (C) 2015 - 2026 Greedysky Studio
7 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12 
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17 
18  * You should have received a copy of the GNU Lesser General Public License along
19  * with this program; If not, see <http://www.gnu.org/licenses/>.
20  ***************************************************************************/
21 
22 #include <thread>
23 #include "ttkmoduleexport.h"
24 
29 {
31 public:
35  TTKSpinLock() = default;
36 
40  void lock() noexcept
41  {
42  while(m_lock.test_and_set(std::memory_order_acquire))
43  {
44  // wait for spin lock to unlock
45  std::this_thread::yield();
46  }
47  }
48 
52  bool try_lock() noexcept
53  {
54  return !m_lock.test_and_set(std::memory_order_acquire);
55  }
56 
60  void unlock() noexcept
61  {
62  m_lock.clear(std::memory_order_release);
63  }
64 
65 private:
66  std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
67 
68 };
69 
74 {
76 public:
80  TTKSpinLockGuard(TTKSpinLock& lock) noexcept
81  : m_lock(lock)
82  {
83  m_lock.lock();
84  }
85 
89  ~TTKSpinLockGuard() noexcept
90  {
91  m_lock.unlock();
92  }
93 
94 private:
96 
97 };
98 
99 
100 // compatiblity for std spin_lock
101 namespace std
102 {
105 
108 }
109 
110 #endif // TTKSPINLOCK_H
#define TTK_MODULE_EXPORT
The class of the spin lock.
Definition: ttkspinlock.h:28
Definition: ttkcompat.h:39
void unlock() noexcept
Definition: ttkspinlock.h:60
TTKSpinLock spin_lock
Definition: ttkspinlock.h:103
TTKSpinLock & m_lock
Definition: ttkspinlock.h:95
TTKSpinLockGuard spin_lock_guard
Definition: ttkspinlock.h:104
~TTKSpinLockGuard() noexcept
Definition: ttkspinlock.h:89
void lock() noexcept
Definition: ttkspinlock.h:40
TTKSpinLockGuard(TTKSpinLock &lock) noexcept
Definition: ttkspinlock.h:80
The class of the spin lock guard.
Definition: ttkspinlock.h:73
#define TTK_DISABLE_COPY(Class)
Definition: ttkqtglobal.h:153
bool try_lock() noexcept
Definition: ttkspinlock.h:52