|
|
@ -2,30 +2,24 @@ package io.legado.app.help.coroutine |
|
|
|
|
|
|
|
|
|
|
|
import kotlinx.coroutines.* |
|
|
|
import kotlinx.coroutines.* |
|
|
|
import kotlinx.coroutines.Dispatchers.IO |
|
|
|
import kotlinx.coroutines.Dispatchers.IO |
|
|
|
import kotlinx.coroutines.sync.Mutex |
|
|
|
|
|
|
|
import kotlinx.coroutines.sync.withLock |
|
|
|
|
|
|
|
import java.util.concurrent.ConcurrentHashMap |
|
|
|
import java.util.concurrent.ConcurrentHashMap |
|
|
|
import java.util.concurrent.ConcurrentLinkedQueue |
|
|
|
|
|
|
|
import java.util.concurrent.PriorityBlockingQueue |
|
|
|
import java.util.concurrent.PriorityBlockingQueue |
|
|
|
|
|
|
|
import java.util.concurrent.atomic.AtomicInteger |
|
|
|
|
|
|
|
|
|
|
|
class OrderCoroutine<T>(val threadCount: Int) { |
|
|
|
class OrderCoroutine<T>(val threadCount: Int) { |
|
|
|
private val taskList = ConcurrentLinkedQueue<suspend CoroutineScope.() -> T>() |
|
|
|
private val taskList = ArrayList<suspend CoroutineScope.() -> T>() |
|
|
|
private val taskResultMap = ConcurrentHashMap<Int, T>() |
|
|
|
private val taskResultMap = ConcurrentHashMap<Int, T>() |
|
|
|
private val finishTaskIndex = PriorityBlockingQueue<Int>() |
|
|
|
private val finishTaskIndex = PriorityBlockingQueue<Int>() |
|
|
|
private val mutex = Mutex() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private suspend fun start() = coroutineScope { |
|
|
|
private suspend fun start() = coroutineScope { |
|
|
|
var taskIndex = 0 |
|
|
|
val taskIndex = AtomicInteger(0) |
|
|
|
|
|
|
|
val tasks = taskList.toList() |
|
|
|
for (i in 1..threadCount) { |
|
|
|
for (i in 1..threadCount) { |
|
|
|
launch { |
|
|
|
launch { |
|
|
|
while (true) { |
|
|
|
while (true) { |
|
|
|
ensureActive() |
|
|
|
ensureActive() |
|
|
|
val task: suspend CoroutineScope.() -> T |
|
|
|
val curIndex = taskIndex.getAndIncrement() |
|
|
|
val curIndex: Int |
|
|
|
val task = tasks.getOrNull(curIndex) ?: return@launch |
|
|
|
mutex.withLock { |
|
|
|
|
|
|
|
task = taskList.poll() ?: return@launch |
|
|
|
|
|
|
|
curIndex = taskIndex++ |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
taskResultMap[curIndex] = task.invoke(this) |
|
|
|
taskResultMap[curIndex] = task.invoke(this) |
|
|
|
finishTaskIndex.add(curIndex) |
|
|
|
finishTaskIndex.add(curIndex) |
|
|
|
} |
|
|
|
} |
|
|
|