[go: up one dir, main page]

Skip to content

Commit

Permalink
C++版本实现线程安全
Browse files Browse the repository at this point in the history
  • Loading branch information
fawdlstty committed Mar 23, 2021
1 parent 259ba88 commit f765be3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
- [x] 同步触发
- [ ] 异步触发
- [x] 测试
- [ ] 线程安全
- [x] 线程安全
- [ ] 撤销触发

### C\#
Expand Down
25 changes: 19 additions & 6 deletions src_cpp/SMLite/SMLite.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <tuple>
#include <vector>

Expand Down Expand Up @@ -185,16 +186,24 @@ namespace Fawdlstty {
SMLite (TState init_state, std::shared_ptr<std::map<TState, std::shared_ptr<_SMLite_ConfigState<TState, TTrigger>>>> _states)
: m_state (init_state), m_states (_states) {}
public:
TState GetState () { return m_state; }
void SetState (TState new_state) { m_state = new_state; }
TState GetState () {
std::unique_lock<std::recursive_mutex> ul (m_mtx);
return m_state;
}
void SetState (TState new_state) {
std::unique_lock<std::recursive_mutex> ul (m_mtx);
m_state = new_state;
}
bool AllowTriggering (TTrigger trigger) {
std::unique_lock<std::recursive_mutex> ul (m_mtx);
if (m_states->find (m_state) != m_states->end ())
return (*m_states) [m_state]->_allow_trigger (trigger);
return false;
}
void Triggering (TTrigger trigger) {
bool Triggering (TTrigger trigger) {
std::unique_lock<std::recursive_mutex> ul (m_mtx);
if (!AllowTriggering (trigger))
throw _SMLite_Exception ("current state cannot launch this trigger.");
return false;
auto _p = (*m_states) [m_state];
auto _state = _p->_trigger (trigger);
if (m_state != _state) {
Expand All @@ -205,11 +214,13 @@ namespace Fawdlstty {
if (_p->m_on_entry)
_p->m_on_entry ();
}
return true;
}
template<typename... Args>
void Triggering (TTrigger trigger, Args... args) {
bool Triggering (TTrigger trigger, Args... args) {
std::unique_lock<std::recursive_mutex> ul (m_mtx);
if (!AllowTriggering (trigger))
throw _SMLite_Exception ("current state cannot launch this trigger.");
return false;
auto _p = (*m_states) [m_state];
auto _state = _p->_trigger (trigger, args...);
if (m_state != _state) {
Expand All @@ -220,11 +231,13 @@ namespace Fawdlstty {
if (_p->m_on_entry)
_p->m_on_entry ();
}
return true;
}

private:
TState m_state;
std::shared_ptr<std::map<TState, std::shared_ptr<_SMLite_ConfigState<TState, TTrigger>>>> m_states;
std::recursive_mutex m_mtx;
};

template<typename TState, typename TTrigger>
Expand Down

0 comments on commit f765be3

Please sign in to comment.