- Mastering High Performance with Kotlin
- Igor Kucherenko
- 256字
- 2021-06-25 20:55:23
The problem of concurrency and parallelism
While concurrency is executing independent subtasks out of order without affecting the final result, parallelism is the executing subtasks that are carried out simultaneously. Parallelism involves concurrency, but concurrency is not necessarily executed in a parallel manner.
The compiler feels free to reorder instructions to perform optimization. This means that there are cases in which accesses to variables, during the execution of a program, may differ from the order specified in the code. Data is moved between registers, caches, and RAM all the time. There are no requirements for the compiler to perform synchronization between threads perfectly because this would cost too much from the performance point of view. This leads to cases when different threads may read different values from the same shared variable. A simplified example of the case described here may look like this:
fun main(vars: Array<String>) {
var sharedVariableA = 0
var sharedVariableB = 0
val threadPool = Executors.newFixedThreadPool(10)
val threadA = Runnable {
sharedVariableA = 3
sharedVariableB = 4
}
val threadB = Runnable {
val localA = sharedVariableA
val localB = sharedVariableB
}
threadPool.submit(threadA)
threadPool.submit(threadB)
}
In a body of the threadB thread, the value of the localA variable is 3, and the value of the localB variable is 4. But if the compiler reorders the operations, the final values of the local variables may differ. To get a better understanding of this issue, we need some knowledge of the internal system of the Java Memory Model.
- Google Apps Script for Beginners
- JavaScript從入門到精通(微視頻精編版)
- Windows系統管理與服務配置
- Rake Task Management Essentials
- Java編程指南:基礎知識、類庫應用及案例設計
- QGIS:Becoming a GIS Power User
- Instant Ext.NET Application Development
- CoffeeScript Application Development Cookbook
- Vue.js 2 Web Development Projects
- 工業機器人離線編程
- MyBatis 3源碼深度解析
- Application Development with Parse using iOS SDK
- 從零開始:C語言快速入門教程
- Java程序設計教程
- C語言程序設計實驗指導