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

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.

主站蜘蛛池模板: 衡阳市| 通许县| 芦溪县| 武功县| 运城市| 安平县| 黎城县| 普洱| 望谟县| 宝山区| 正安县| 沐川县| 调兵山市| 罗江县| 舒兰市| 新干县| 丘北县| 孟连| 农安县| 睢宁县| 湘潭县| 怀集县| 连南| 沂源县| 临沂市| 元阳县| 永吉县| 灵石县| 高雄县| 和硕县| 清涧县| 石渠县| 思茅市| 林周县| 楚雄市| 延津县| 诸城市| 通许县| 巴彦淖尔市| 思南县| 绩溪县|