From 867a7c4ff77c207f85f4c417f4575fec543c3ac8 Mon Sep 17 00:00:00 2001 From: Project_IO Date: Mon, 23 Sep 2024 17:48:05 +0900 Subject: [PATCH] feat: async task container - not worked --- .../p/x32/api/util/AsyncTaskContainer.kt | 70 +++++++++++++++++++ .../net/projecttl/p/x32/kernel/TaskManager.kt | 4 ++ 2 files changed, 74 insertions(+) create mode 100644 px32-bot-api/src/main/kotlin/net/projecttl/p/x32/api/util/AsyncTaskContainer.kt create mode 100644 px32-bot-core/src/main/kotlin/net/projecttl/p/x32/kernel/TaskManager.kt diff --git a/px32-bot-api/src/main/kotlin/net/projecttl/p/x32/api/util/AsyncTaskContainer.kt b/px32-bot-api/src/main/kotlin/net/projecttl/p/x32/api/util/AsyncTaskContainer.kt new file mode 100644 index 0000000..3da608e --- /dev/null +++ b/px32-bot-api/src/main/kotlin/net/projecttl/p/x32/api/util/AsyncTaskContainer.kt @@ -0,0 +1,70 @@ +package net.projecttl.p.x32.api.util + +import kotlinx.coroutines.sync.Mutex + +/* + * This class only support by kotlin + * This feature is Experimental + */ +class AsyncTask(val loop: Boolean = true, val block: suspend () -> Unit) { + private val memLock = Mutex() + var isActive = true + private set + + suspend fun run() { + do { + if (memLock.isLocked) { + if (!isActive) { + break + } + + continue + } + + block.invoke() + } while (loop) + } + + suspend fun kill() { + memLock.lock() + isActive = false + + memLock.unlock() + } +} + +/* + * This class only support by kotlin + * This feature is Experimental + */ +class AsyncTaskContainer { + private val tasks = mutableMapOf() + private var tid = 0L + + fun getTask(tid: Long): AsyncTask? { + return tasks[tid] + } + + fun createTask(task: AsyncTask) { + tasks[tid] = task + println("created task with id: $tid") + + tid++ + } + + suspend fun removeTask(tid: Long) { + val task = getTask(tid) ?: throw NullPointerException("task $tid is missing or not defined") + task.kill() + + tasks.remove(tid) + println("removed task with id: $tid") + } + + suspend fun killAll() { + tasks.forEach { (k, t) -> + t.kill() + tasks.remove(k) + println("removed task with id: $tid") + } + } +} \ No newline at end of file diff --git a/px32-bot-core/src/main/kotlin/net/projecttl/p/x32/kernel/TaskManager.kt b/px32-bot-core/src/main/kotlin/net/projecttl/p/x32/kernel/TaskManager.kt new file mode 100644 index 0000000..9460b78 --- /dev/null +++ b/px32-bot-core/src/main/kotlin/net/projecttl/p/x32/kernel/TaskManager.kt @@ -0,0 +1,4 @@ +package net.projecttl.p.x32.kernel + +object TaskManager { +} \ No newline at end of file