MeshLib
 
Loading...
Searching...
No Matches
MRAsyncTimer.h
Go to the documentation of this file.
1#pragma once
2
3#include "exports.h"
4#include <mutex>
5#include <condition_variable>
6#include <chrono>
7#include <optional>
8#ifndef __EMSCRIPTEN__
9#include <thread>
10#include <functional>
11#include <memory>
12#endif
13
14namespace MR
15{
16
17using Time = std::chrono::time_point<std::chrono::system_clock>;
18
19// the object to set timer from any thread and wait for alert time from another thread
20class MRVIEWER_CLASS AsyncTimer
21{
22public: //to call from any requester thread
23 // sets alert time, forgetting about previous time
24 MRVIEWER_API void setTime( const Time& time );
25 // sets alert time only if it is not set yet
26 // returns true if timer set
27 MRVIEWER_API bool setTimeIfNotSet( const Time& time );
28 // reset the timer
29 MRVIEWER_API void resetTime();
30 // orders the waiter thread to stop
31 MRVIEWER_API void terminate();
32
33public: //to call from waiter thread
34 enum class Event
35 {
36 AlertTimeReached,
37 Terminate
38 };
39 MRVIEWER_API Event waitBlocking();
40
41private:
42 std::mutex mutex_;
43 std::condition_variable cvar_;
44 std::optional<Time> time_;
45 bool terminating_ = false;
46};
47
48#ifndef __EMSCRIPTEN__
49// Complete given command in given time
50// may know only one command at a time
51// terminate listener in destructor
52class MRVIEWER_CLASS AsyncRequest
53{
54public:
55 MRVIEWER_API AsyncRequest();
56 MRVIEWER_API ~AsyncRequest();
57 using Command = std::function<void()>;
58
59 // requests command execution, forgetting about previous command
60 // note that command will be executed from the listener thread
61 MRVIEWER_API void request( const Time& time, Command command );
62
63 // requests command execution only if no request waiting
64 // note that command will be executed from the listener thread
65 MRVIEWER_API void requestIfNotSet( const Time& time, Command command );
66
67 // clears command
68 MRVIEWER_API void reset();
69private:
70 std::thread listenerThread_;
71 AsyncTimer timer_;
72
73 Command loadCommand_();
74 void storeCommand_( Command command );
75
76 std::mutex cmdMutex_;
77 Command command_;
78
79};
80#endif
81} //namespace MR
Definition MRAsyncTimer.h:53
MRVIEWER_API void requestIfNotSet(const Time &time, Command command)
MRVIEWER_API void request(const Time &time, Command command)
MRVIEWER_API void reset()
std::function< void()> Command
Definition MRAsyncTimer.h:57
MRVIEWER_API AsyncRequest()
MRVIEWER_API ~AsyncRequest()
Definition MRAsyncTimer.h:21
MRVIEWER_API void setTime(const Time &time)
MRVIEWER_API void resetTime()
MRVIEWER_API Event waitBlocking()
MRVIEWER_API bool setTimeIfNotSet(const Time &time)
Event
Definition MRAsyncTimer.h:35
MRVIEWER_API void terminate()
Definition MRCameraOrientationPlugin.h:7
std::chrono::time_point< std::chrono::system_clock > Time
Definition MRAsyncTimer.h:17