Skip to content
This repository has been archived by the owner on Apr 26, 2020. It is now read-only.

Commit

Permalink
所有修改状态操作加锁
Browse files Browse the repository at this point in the history
Signed-off-by: YangDR <[email protected]>
  • Loading branch information
YdrMaster committed Sep 13, 2018
1 parent 50f0914 commit 2897baf
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions src/main/kotlin/org/mechdancer/statemachine/core/StandardMachine.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ class StandardMachine<T : IState>(origin: T? = null)
//状态转移互斥锁
private val lock = Any()

//直接转移
private fun jump(target: T?) =
synchronized(lock) { current = target }

//按检查结果转移
private infix fun Event.thenTransfer(target: T?) =
private infix fun Event.thenJump(target: T?) =
synchronized(lock) { this().then { current = target } }

//检查能否发生某个转移
Expand All @@ -46,7 +50,7 @@ class StandardMachine<T : IState>(origin: T? = null)
get() = current === null

override fun event(pair: Pair<T, T>) =
{ { current === pair.first && check(pair) } thenTransfer pair.second }
{ { current === pair.first && check(pair) } thenJump pair.second }

override infix fun register(pair: Pair<T, T>) =
event(pair).also {
Expand All @@ -59,39 +63,34 @@ class StandardMachine<T : IState>(origin: T? = null)
}

override operator fun invoke() {
current?.let { last ->
last.doing();
{ current === last } thenTransfer select(last)
current?.also {
it.doing(); //执行一次,执行后仍未发生状态转移则触发一次跳转
{ current === it } thenJump select(it)
}
}

override infix fun transfer(target: T?) =
{ check(current to target) } thenTransfer target
{ check(current to target) } thenJump target

override infix fun goto(target: T?) =
{ check(null to target) } thenTransfer target
{ check(null to target) } thenJump target

override fun reset() = transfer(origin)

override fun startFrom(newOrigin: T) =
isCompleted.then {
origin = newOrigin
reset()
jump(origin)
}

override fun stop() {
goto(null)
}
override fun stop() = jump(null)

override fun transferNow() =
current?.let { last ->
current = select(last)
true
} ?: false
current?.let { jump(select(it)); true } ?: false

override fun gotoNext() =
current?.let { last ->
current = targets[last]?.firstOrNull { check(null to it) }
current?.let {
jump(targets[it]?.firstOrNull { target -> check(null to target) })
true
} ?: false

Expand Down

0 comments on commit 2897baf

Please sign in to comment.