官术网_书友最值得收藏!

Deadlocks

Often, in order to guarantee that concurrent code is synchronized correctly, it's necessary to suspend or block execution while a task is completed in a different thread. But due to the complexity of these situations, it isn't uncommon to end up in a situation where the execution of the complete application is halted because of circular dependencies:

lateinit var jobA : Job
lateinit var jobB : Job

fun main(args: Array<String>) = runBlocking {
jobA = launch {
delay(1000)
// wait for JobB to finish
jobB.join()
}

jobB = launch {
// wait for JobA to finish
jobA.join()
}

// wait for JobA to finish
jobA.join()
println("Finished")
}

Let's take a look at a simple flow diagram of jobA.

Flow chart of jobA

In this example, jobA is waiting for jobB to finish its execution; meanwhile jobB is waiting for jobA to finish. Since both are waiting for each other, none of them is ever going to end; hence the message Finished will never be printed:

Flow chart of jobB

This example is, of course, intended to be as simple as possible, but in real-life scenarios deadlocks are more difficult to spot and correct. They are commonly caused by intricate networks of locks, and often happen hand-in-hand with race conditions. For example, a race condition can create an unexpected state in which the deadlock can happen.

主站蜘蛛池模板: 彰化市| 浮山县| 隆尧县| 东明县| 精河县| 丘北县| 邛崃市| 阿合奇县| 宁强县| 鄂托克前旗| 苍梧县| 嘉祥县| 黔东| 宁津县| 霍邱县| 富民县| 长岛县| 海林市| 翁牛特旗| 监利县| 岳西县| 池州市| 伊吾县| 天门市| 阳信县| 拜泉县| 伊金霍洛旗| 色达县| 玛沁县| 包头市| 法库县| 葵青区| 若尔盖县| 隆化县| 通榆县| 云梦县| 河曲县| 乐清市| 琼结县| 汤阴县| 临武县|