当前位置:网站首页>Three core issues of concurrent programming - "deep understanding of high concurrent programming"
Three core issues of concurrent programming - "deep understanding of high concurrent programming"
2022-07-03 01:32:00 【Little brother Fu】
Continue to adhere to the original output , Click on the blue word to follow me
author : Little brother Fu
Blog :https://bugstack.cn
*precipitation 、 Share 、 grow up , Let yourself and others have something to gain !
*
One 、 Division of labor
1. Analogy with real cases
2. Division of labor in concurrent programming
Two 、 Synchronization problem
1. Analogy with real cases
2. Synchronization in concurrent programming
3、 ... and 、 The problem of mutual exclusion
1. Analogy with real cases
2. Mutual exclusion in concurrent programming
Four 、 Send five books
Activity description
50% off
Three core problems of concurrent programming
Concurrent programming is not an isolated technology , Nor is it a technology that is divorced from the real life scene .
contrary , Concurrent programming is a comprehensive technology , meanwhile , It is related to real life There is a close connection between the scenes of .
There are three core issues in concurrent programming :
Division of labor Synchronization problem The problem of mutual exclusion
This paper gives a brief introduction to these three core issues .
One 、 Division of labor
About division of labor , The more official explanation is : A relatively large task is split into multiple tasks of appropriate size , These tasks of the right size are given to the right thread to execute .
The division of labor emphasizes the performance of execution .
1. Analogy with real cases
The division of labor can be understood by analogy with the scenes in real life , for example , If you are a listed company CEO, that , Your main job is to plan the strategic direction of the company and manage the company well . In terms of how to manage the company , There are many tasks involved .
here , It can be seen as a big task to manage the company well , This big task can include personnel recruitment and management 、 The product design 、 product development 、 Product operation 、 Product promotion 、 Tax statistics and calculation, etc . If these tasks are assigned to CEO Do it alone , So estimate CEO You will get tired and lie down .CEO One person finishes all the daily work of the company, as shown in the figure 1 Shown .
Pictured 1 Shown , company CEO It is a very undesirable way for one person to finish all the daily work of the company , This will make the company unable to operate normally , So how to do it ?
There is a good way to break down the daily work of the company , Hand over the recruitment and management of personnel to the human resources department , Will produce The product design work is handed over to the design department , Hand over the product development work to the R & D department , Hand over the product operation and product promotion to Yun Sales and marketing department , Hand over the company's tax statistics and calculation to the finance department .
such ,CEO The focus of our work has become to keep abreast of the work of each department , Coordinate and coordinate the work of all departments , And think about how to plan the company's strategy .
The daily work of the company after division of labor is shown in the figure 2 Shown .
Divide the daily work of the company , You can find , The work among departments can be carried out in parallel . for example , When the human resources department conducts employee performance appraisal , The design department and R & D department are designing and developing the company's products , meanwhile , The company's operators are communicating with designers and R & D personnel on how to better improve the company's products , The marketing department is making greater efforts to publicize and promote the company's products , The finance department is counting and calculating various financial statements of the company . Everything is so orderly .
therefore , in real life , It is very important to arrange the right people to do the right things . Mapping to the realm of concurrent programming The same is true .
2. Division of labor in concurrent programming
In concurrent programming , It is also necessary to split a large task into several smaller tasks , And give these small tasks to Different threads execute , Pictured 3 Shown .
In concurrent programming , Because multiple threads can execute concurrently , Therefore, it can improve the execution efficiency of the task to a certain extent .
In the field of concurrent programming , One more thing to note is : Assign tasks to appropriate threads to do . in other words , Don't leave the task performed by the main thread to the child thread , otherwise , There is no way to solve the problem .
It's like a company's CEO It is the same as handing over the planning of the company's future work to a product developer , Not only can not plan the future of the company , It can even run counter to the company's values .
stay Java in , Thread pool 、Fork/Join The framework and Future Interfaces are all ways to realize division of labor . In multithreaded design pattern ,Guarded Suspension Pattern 、Thread-Per-Message Pattern 、 producer — Consumer model 、 Two stage termination mode 、Worker-Thread Patterns and Balking Patterns are the implementation of division of labor .
Two 、 Synchronization problem
In concurrent programming , Synchronization refers to a thread executing its own tasks , How to notify other threads to continue the task , It can also be understood as collaboration between threads , Synchronization emphasizes the performance of execution .
1. Analogy with real cases
You can find cases similar to the synchronization problem in concurrent programming in real life .
for example , Zhang San 、 Li Si and Wang Wu jointly developed a project , Zhang San is a front-end developer , He needs to wait for Lisi's development interface task to complete before he starts rendering page , Li Si needs to wait for Wang Wu's service development to complete before writing the interface .
in other words , There is a dependency between tasks , When the task ahead is finished , To perform the following tasks .
in real life , This synchronization of tasks , It is more realized by the exchange and communication between people . for example , Wang Wu's service development task has been completed , Tell Li Si , Li Si immediately began to implement the task of developing interfaces . After Li Si's interface development is completed , Tell Zhangsan again , Zhang San immediately calls the interface developed by Li Si to render the returned data to the page . in real life The synchronization model of is shown in the figure 4 Shown .
From the figure 4 It can be seen that , in real life , Zhang San 、 There is a dependency between the tasks of Li Si and Wang Wu , Zhang San's task of rendering the page depends on Li Si's task of developing the interface , Li Si's task of developing interfaces depends on Wang Wu's task of developing services .
2. Synchronization in concurrent programming
In the field of concurrent programming , The synchronization mechanism refers to the task execution of a thread , How to notify other threads to continue executing tasks , The simple model of concurrent programming synchronization is shown in the figure 5 Shown .
From the figure 5 It can be seen that , In concurrent programming , Tasks between multiple threads are dependent .
Threads A Need to block the waiting thread B The task cannot be executed until the task is completed , Threads B Need to block the waiting thread C The task cannot be executed until the task is completed . Threads C After executing the task, the thread will wake up B Go ahead with the task , Threads B After executing the task, the thread will wake up A Go ahead with the task .
This synchronization mechanism between threads , You can use the following if Pseudo code to represent .
if( Dependent task completion ){
Perform the current task
}else{
Continue to wait for the execution of dependent tasks
}
Above if What pseudo code means is : When the dependent task is completed , Perform the current task , otherwise , Continue to wait Depend on the execution of the task .
In the real world , It is often necessary to judge whether the dependent task has been completed in time , It can be used at this time while Follow Ring instead of if Judge , while The pseudocode is as follows .
while( Dependent tasks are not completed ){
Continue to wait for the execution of dependent tasks
}
Perform the current task
Above while What pseudo code means is : If the dependent task is not completed , Then wait all the time , Until the dependent task is completed , To execute the current task .
In the field of concurrent programming , The synchronization mechanism has a very classic model —— producer — Consumer model . If the queue is full , Then the producer thread needs to wait , If the queue is not satisfied , You need to wake up the producer thread ; If the queue is empty , Then the consumer thread needs to wait , If the queue is not empty , You need to wake up consumers .
The following pseudocode can be used to represent the producer — Consumer model .
Producer pseudocode
while( The queue is full ){
Producer thread waiting
}
Wake up producers
Consumer pseudocode
while( The queue is empty ){
Consumer waiting
}
Wake up consumers
stay Java in ,Semaphore、Lock、synchronized.、CountDownLatch、CyclicBarrier、Exchanger and Phaser And other tool classes or frameworks have implemented the synchronization mechanism .
3、 ... and 、 The problem of mutual exclusion
In concurrent programming , The mutual exclusion problem generally refers to that only one thread is allowed to access the shared resources in the critical area at the same time . Mutex emphasizes the correctness of multiple threads executing tasks .
1. Analogy with real cases
A typical scenario of mutual exclusion problem in reality is that multiple vehicles at an intersection merge into a one-way street , Pictured 6 Shown .
From the picture 6 It can be seen that , When multiple vehicles cross an intersection and join the same one-way street , As the entrance of the one-way street can only accommodate one vehicle , So other vehicles need to wait for the vehicles in front to pass through the one-way street entrance , Then pass through the entrance of one-way street orderly . This is the mutually exclusive scene in real life .
2. Mutual exclusion in concurrent programming
In concurrent programming , Division and synchronization emphasize the performance of tasks , Mutual exclusion emphasizes the correctness of task execution , That is, thread safety .
If in concurrent programming , Multiple threads enter the critical area to access the same shared variable at the same time , Thread safety problems may arise , This is determined by the atomicity of threads 、 Visibility and order issues .
And solve atomicity in concurrent programming 、 The core solution to the visibility and ordering problem is the mutual exclusion between threads .
for example , have access to JVM Provided in synchronized Lock to realize mutual exclusion between multiple threads , Use synchronized The pseudo code of the lock is as follows .
Modification methods
public synchronized void methodName(){
// Omit the specific method
}
Decorated code block
public void methodName(){
synchronized(this){
// Omit the specific method
}
}
public void methodName(){
synchronized(obj){
// Omit the specific method
}
}
public void methodName(){
synchronized(ClassName.class){
// Omit the specific method
}
}
Modified static method
public synchronized static void staticMethodName(){
// Omit the specific method
}
except synchronized lock ,Java It also provides ThreadLocal、CAS、 Atomic classes and with CopyOnWrite The first concurrent container class 、Lock Lock and read / Write locks, etc. , They all implement the mutual exclusion mechanism of threads .
This article is excerpted from 《 Deep understanding of high concurrency programming : Core principles and case practice 》, This paper mainly introduces three core problems in concurrent programming : Division of labor 、 Synchronization and mutual exclusion , And enumerate the scenes in real life for analogy , So that readers can understand these three core issues . Welcome to this book to learn more about concurrent programming .
Four 、 Send five books
Give 5 Ben 《 Deep understanding of high concurrency programming : Core principles and case practice 》, The rules : Leave a message about this article and forward it to the circle of friends , Invite your partner to leave a message give the thumbs-up , ranking 1、2、3、4、5 Five fan partners of , One book per person .
Activity description
Time range :2022-06-29 07:55:00 - 2022-06-30 19:00:00 Publication time :2022 year 06 month 30 Japan , Thursday , The news of winning the prize is announced at the top of this message
50% off
- END -
Scan the code below to pay attention to bugstack Wormhole stack , Learn and grow together with Xiaofu 、 Common progress , Making a yard is the most expensive Coder!
reply 【 Design patterns 】, obtain 《 Relearning Java Design patterns 》, This is a practical book of real Internet cases , Pull away from the actual business , transaction 、 marketing 、 seckill 、 middleware 、 Source code and many other scenarios for learning code design . reply 【Spring special column 】, obtain 《 Hand rolling Spring》, This is a book By taking the reader Simplified handwritten version Spring frame , understand Spring IOC、AOP、 Circular dependence, etc Core principles and Design Realization Technology Information . reply 【 Face to face manual 】, obtain 《 Face to face manual • Nada factory Offer》, This is a book with depth Java Core content , From data structure 、 Algorithm 、 Concurrent programming and JVM system 8 Continuous in-depth explanation , Let understand is really understand .
java
The engineer 、 Architects , Developed transactions & marketing 、 I've written about operations & Activities 、 I've designed middleware and repeater 、IO card . It's not just about writing Java Language , I did C#、PHP, He's a technically active tosser . This article is from WeChat official account. - bugstack Wormhole stack (bugstack).
If there is any infringement , Please contact the [email protected] Delete .
Participation of this paper “OSC Source creation plan ”, You are welcome to join us , share .
边栏推荐
- [Androd] Gradle 使用技巧之模块依赖替换
- The difference between tail -f, tail -f and tail
- 【FH-GFSK】FH-GFSK信号分析与盲解调研究
- [技术发展-23]:DSP在未来融合网络中的应用
- wirehark数据分析与取证A.pacapng
- Makefile中wildcard、patsubst、notdir的含义
- Leetcode 6103 - minimum fraction to delete an edge from the tree
- Is there a handling charge for spot gold investment
- 海量数据冷热分离方案与实践
- Button wizard play strange learning - automatic return to the city route judgment
猜你喜欢
MySQL foundation 05 DML language
【数据挖掘】任务5:K-means/DBSCAN聚类:双层正方形
力扣 204. 计数质数
传输层 TCP主要特点和TCP连接
MySQL - database query - condition query
音程的知识的总结
Basis of information entropy
Using tensorboard to visualize the model, data and training process
Learn the five skills you need to master in cloud computing application development
C#应用程序界面开发基础——窗体控制(2)——MDI窗体
随机推荐
[flutter] icons component (fluttericon Download Icon | customize SVG icon to generate TTF font file | use the downloaded TTF icon file)
Uniapp component -uni notice bar notice bar
Why can't the start method be called repeatedly? But the run method can?
Database SQL language 02 connection query
Give you an array numbers that may have duplicate element values. It was originally an array arranged in ascending order, and it was rotated once according to the above situation. Please return the sm
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-9
SwiftUI 组件大全之使用 SceneKit 和 SwiftUI 构建交互式 3D 饼图(教程含源码)
Now that the teenager has returned, the world's fireworks are the most soothing and ordinary people return to work~
对非ts/js文件模块进行类型扩充
What operations need attention in the spot gold investment market?
Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads
Arduino dy-sv17f automatic voice broadcast
[self management] time, energy and habit management
CF1617B Madoka and the Elegant Gift、CF1654C Alice and the Cake、 CF1696C Fishingprince Plays With Arr
MySQL foundation 06 DDL
【第29天】给定一个整数,请你求出它的因子数
wirehark数据分析与取证A.pacapng
Key wizard play strange learning - multithreaded background coordinate recognition
软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
openresty 缓存