TTKMusicPlayer  4.2.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 - 2025 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:
32  TTKSpinLock() = default;
33 
34  void lock() noexcept
35  {
36  while(m_lock.test_and_set(std::memory_order_acquire))
37  {
38  // wait for spin lock to unlock
39  std::this_thread::yield();
40  }
41  }
42 
43  bool try_lock() noexcept
44  {
45  return !m_lock.test_and_set(std::memory_order_acquire);
46  }
47 
48  void unlock() noexcept
49  {
50  m_lock.clear(std::memory_order_release);
51  }
52 
53 private:
54  std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
55 
56 };
57 
62 {
64 public:
65  TTKSpinLockGuard(TTKSpinLock& lock) noexcept
66  : m_lock(lock)
67  {
68  m_lock.lock();
69  }
70 
71  ~TTKSpinLockGuard() noexcept
72  {
73  m_lock.unlock();
74  }
75 
76 private:
78 
79 };
80 
81 
82 // compatiblity for std spin_lock
83 namespace std
84 {
87 
90 }
91 
92 #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:48
TTKSpinLock spin_lock
Definition: ttkspinlock.h:85
TTKSpinLock & m_lock
Definition: ttkspinlock.h:77
TTKSpinLockGuard spin_lock_guard
Definition: ttkspinlock.h:86
~TTKSpinLockGuard() noexcept
Definition: ttkspinlock.h:71
void lock() noexcept
Definition: ttkspinlock.h:34
TTKSpinLockGuard(TTKSpinLock &lock) noexcept
Definition: ttkspinlock.h:65
The class of the spin lock guard.
Definition: ttkspinlock.h:61
#define TTK_DISABLE_COPY(Class)
Definition: ttkqtglobal.h:153
bool try_lock() noexcept
Definition: ttkspinlock.h:43