sptk2 logo
SPTK Home Page
Loop.h
1/*
2╔══════════════════════════════════════════════════════════════════════════════╗
3║ SIMPLY POWERFUL TOOLKIT (SPTK) ║
4╟──────────────────────────────────────────────────────────────────────────────╢
5║ copyright © 1999-2022 Alexey Parshin. All rights reserved. ║
6║ email alexeyp@gmail.com ║
7╚══════════════════════════════════════════════════════════════════════════════╝
8┌──────────────────────────────────────────────────────────────────────────────┐
9│ This library is free software; you can redistribute it and/or modify it │
10│ under the terms of the GNU Library General Public License as published by │
11│ the Free Software Foundation; either version 2 of the License, or (at your │
12│ option) any later version. │
13│ │
14│ This library is distributed in the hope that it will be useful, but │
15│ WITHOUT ANY WARRANTY; without even the implied warranty of │
16│ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library │
17│ General Public License for more details. │
18│ │
19│ You should have received a copy of the GNU Library General Public License │
20│ along with this library; if not, write to the Free Software Foundation, │
21│ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. │
22│ │
23│ Please report all bugs and problems to alexeyp@gmail.com. │
24└──────────────────────────────────────────────────────────────────────────────┘
25*/
26
27#pragma once
28
29#include <list>
30#include <mutex>
31#include <sptk5/Exception.h>
32
33template<class T>
34class Loop
35{
36 mutable std::mutex m_mutex;
37 std::list<T> m_list;
38 typename std::list<T>::iterator m_position;
39
40public:
41 Loop()
42 {
43 m_position = m_list.end();
44 }
45
46 void clear()
47 {
48 std::scoped_lock lock(m_mutex);
49 m_position = m_list.end();
50 m_list.clear();
51 }
52
53 void add(const T& data)
54 {
55 std::scoped_lock lock(m_mutex);
56 m_list.push_back(data);
57 m_position = m_list.end();
58 --m_position;
59 }
60
61 T& get()
62 {
63 std::scoped_lock lock(m_mutex);
64 if (m_list.empty())
65 throw sptk::Exception("Loop is empty");
66 return *m_position;
67 }
68
69 T& loop()
70 {
71 std::scoped_lock lock(m_mutex);
72 if (m_list.empty())
73 throw sptk::Exception("Loop is empty");
74 ++m_position;
75 if (m_position == m_list.end())
76 m_position = m_list.begin();
77 return *m_position;
78 }
79
80 size_t size() const
81 {
82 std::scoped_lock lock(m_mutex);
83 return m_list.size();
84 }
85};
Definition: Loop.h:35
SPTK generic exception class.
Definition: Exception.h:56

Fri Oct 14 2022 09:58:31: SPTK 5.4.1