Kotlin-协程表现异常

时间:2019-10-11 14:15:33

标签: kotlin kotlin-coroutines

该问题与我之前的问题之一相关:Kotlin - Coroutines with loops

所以,这是我当前的实现方式:

fun propagate() = runBlocking {
    logger.info("Propagating objectives...")
    val variablesWithSetObjectives: List<ObjectivePropagationMapping> =
        variables.filter { it.variable.objective != Objective.NONE }
    variablesWithSetObjectives.forEach { variableWithSetObjective ->
        logger.debug("Propagating objective ${variableWithSetObjective.variable.objective} from variable ${variableWithSetObjective.variable.name}")
        val job: Job = launch {
            propagate(variableWithSetObjective, variableWithSetObjective.variable.objective, this, variableWithSetObjective)
        }
        job.join()
        traversedVariableNames.clear()
    }
    logger.info("Done")
}

private tailrec fun propagate(currentVariable: ObjectivePropagationMapping, objectiveToPropagate: Objective, coroutineScope: CoroutineScope, startFromVariable: ObjectivePropagationMapping? = null) {
    if (traversedVariableNames.contains(currentVariable.variable.name)) {
        logger.debug("Detected loopback condition, stopping propagation to prevent loop")
        return
    }
    traversedVariableNames.add(currentVariable.variable.name)
    val objectiveToPropagateNext: Objective =
        if (startFromVariable != currentVariable) {
            logger.debug("Propagating objective $objectiveToPropagate to variable ${currentVariable.variable.name}")
            computeNewObjectiveForVariable(currentVariable, objectiveToPropagate)
        }
        else startFromVariable.variable.objective
    logger.debug("Choosing variable to propagate to next")
    val variablesToPropagateToNext: List<ObjectivePropagationMapping> =
        causalLinks
            .filter { it.toVariable.name == currentVariable.variable.name }
            .map { causalLink -> variables.first { it.variable.name == causalLink.fromVariable.name } }
    if (variablesToPropagateToNext.isEmpty()) {
        logger.debug("Detected end of path, stopping propagation...")
        return
    }
    val variableToPropagateToNext: ObjectivePropagationMapping = variablesToPropagateToNext.random()
    logger.debug("Chose variable ${variableToPropagateToNext.variable.name} to propagate to next")
    if (variablesToPropagateToNext.size > 1) {
        logger.debug("Detected split condition")
        variablesToPropagateToNext.filter { it != variableToPropagateToNext }.forEach {
            logger.debug("Launching child thread for split variable ${it.variable.name}")
            coroutineScope.launch {
                propagate(it, objectiveToPropagateNext, this)
            }
        }
    }
    propagate(variableToPropagateToNext, objectiveToPropagateNext, coroutineScope)
}

我目前正在以下变量拓扑上运行该算法(请注意,算法遵循的箭头指向变量,但箭头不指向变量): Variable topology

目前,我得到以下调试打印结果:https://pastebin.com/ya2tmc6s

如您所见,即使我启动了协程,它们也不会开始执行,直到主要的递归递归函数完成了探索完整路径为止。

我希望启动的协程立即开始执行...

1 个答案:

答案 0 :(得分:1)

除非另有说明,否则您在runBlocking中启动的所有协程将在同一线程上运行。

如果要启用多线程,可以将其更改为runBlocking(Dispatchers.Default)。我只是假设所有这些代码都是线程安全的。

如果您真的不想启用多线程,那么您实际上不必关心协程以什么顺序运行。