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

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.

主站蜘蛛池模板: 大石桥市| 三明市| 隆安县| 张家口市| 广宗县| 视频| 嘉定区| 金昌市| 桐城市| 息烽县| 牟定县| 华容县| 鲁山县| 久治县| 嘉峪关市| 石屏县| 吴旗县| 桃源县| 兰溪市| 琼中| 巴楚县| 巩留县| 扶余县| 青冈县| 邯郸县| 金阳县| 来安县| 凤阳县| 五原县| 通江县| 沈阳市| 布尔津县| 旬邑县| 威海市| 错那县| 桂东县| 东兰县| 武穴市| 周宁县| 雷州市| 宜昌市|