PicoScenes API Docs
 
Loading...
Searching...
No Matches
FIFOWaitBlocker.hxx
Go to the documentation of this file.
1//
2// Created by 蒋志平 on 2024/10/17.
3//
4
5#ifndef FIFOWAITBLOCKER_HXX
6#define FIFOWAITBLOCKER_HXX
7
8#include <condition_variable>
9#include <deque>
10#include <thread>
11#include <map>
12
14public:
15 static std::shared_ptr<FIFOWaitBlocker> getInstance(const std::string& instanceName) {
16 std::lock_guard<std::mutex> lock(instanceMutex); // 加锁
17 static std::map<std::string, std::shared_ptr<FIFOWaitBlocker>> instanceMap;
18 if (!instanceMap.contains(instanceName)) {
19 instanceMap[instanceName] = std::shared_ptr<FIFOWaitBlocker>(new FIFOWaitBlocker());
20 }
21
22 return instanceMap[instanceName];
23 }
24
26 std::lock_guard guard(queueMutex);
27 threadWaitQueue.emplace_back(std::this_thread::get_id());
28 }
29
30 [[nodiscard]] bool isThisThreadsTurn() {
31 std::lock_guard guard(queueMutex);
32 return !threadWaitQueue.empty() && threadWaitQueue.front() == std::this_thread::get_id();
33 }
34
35 void exit() {
36 auto id = std::this_thread::get_id();
37 std::lock_guard guard(queueMutex);
38 std::erase_if(threadWaitQueue, [id](const std::thread::id& currentId) {
39 return currentId == id;
40 });
41 }
42
43private:
44
45 std::mutex queueMutex;
46 std::deque<std::thread::id> threadWaitQueue;
47
48private:
49 static std::mutex instanceMutex; // 全局锁,保护 instanceMap
50 FIFOWaitBlocker() = default;
51};
52std::mutex FIFOWaitBlocker::instanceMutex;
53#endif //FIFOWAITBLOCKER_HXX
static std::shared_ptr< FIFOWaitBlocker > getInstance(const std::string &instanceName)