-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
task processor, add locations to parser combinator
- Loading branch information
alexander.nutz
committed
Apr 3, 2024
1 parent
5654609
commit 25086a3
Showing
2 changed files
with
86 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package blitz.async | ||
|
||
import blitz.collections.SynchronizedList | ||
import blitz.logic.then | ||
|
||
abstract class Processor { | ||
protected val tasks = SynchronizedList(mutableListOf<Task>()) | ||
|
||
|
||
fun tick() { | ||
for (task in tasks) { | ||
if (task.counter >= task.priority) { | ||
task.fn() | ||
task.counter = 0 | ||
} else { | ||
task.counter ++ | ||
} | ||
} | ||
} | ||
|
||
abstract fun add(task: Task) | ||
|
||
abstract fun remove(task: Task) | ||
|
||
/** priority 0 means every tick; 1 means every second tick; 2 means every third tick, ... */ | ||
data class Task( | ||
internal val priority: Int = 0, // every tick | ||
internal val fn: () -> Unit | ||
) { | ||
internal var counter: Int = 0 | ||
} | ||
|
||
companion object { | ||
fun singleThread(): Processor = | ||
SingleThreadProcessor() | ||
|
||
fun manualTick(): Processor = | ||
object : Processor() { | ||
override fun add(task: Task) { | ||
tasks.add(task) | ||
} | ||
|
||
override fun remove(task: Task) { | ||
tasks.remove(task) | ||
} | ||
} | ||
} | ||
} | ||
|
||
internal class SingleThreadProcessor: Processor() { | ||
private fun createThread() = Thread { while (true) { tick() } } | ||
|
||
private var thread: Thread? = null | ||
|
||
override fun add(task: Task) { | ||
tasks.add(task) | ||
if (thread == null) { | ||
thread = createThread() | ||
thread!!.start() | ||
} | ||
} | ||
|
||
override fun remove(task: Task) { | ||
tasks.remove(task) | ||
tasks.isEmpty().then { | ||
runCatching { thread?.interrupt() } | ||
thread = null | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters