当前位置:网站首页>[swoole series 3.1] have you been asked about processes, threads, and collaborations during the interview?
[swoole series 3.1] have you been asked about processes, threads, and collaborations during the interview?
2022-07-26 19:04:00 【Ma Nong Lao Zhang ZY】
process 、 Threads 、 coroutines , Have you been asked about the interview ?
Finally started , People are most concerned about , It's also a problem we often encounter in interviews . I believe many students will have experienced this question raised by the interviewer . If your major is computer related , Then the problem is very simple , But if you're not , Then it's really necessary to make up lessons .
Process related issues , In computer major, it is generally explained in the operating system . But I also said in the course related to data structure before , I'm not a computer major , So , This question is really confused for me before . Through these years, I have learned some knowledge related to the operating system , Have some understanding of , And it is really limited to the level of understanding , There is no particularly in-depth study and experiment , So please correct all kinds of mistakes in today's content .
process
process , The simplest understanding is the software we run . It is the execution process of a program . for instance , you are here Windows It's on QQ , Then go to the task manager and you can see a QQ.exe The program of is being executed . This thing is called process .
The process starts and ends , We shut it down QQ , natural QQ The corresponding process is over . For the server operating system , Our service applications are generally not restarted , But it does have the possibility of ending . For example, upgrade the server , Modify the configuration file and so on .
Drive more QQ , Or just like when we played games, we played more games , In fact, it is the application of multiple processes . in addition , Process also has the concept of sub process , It calls the operating system fork() Function created , Generally, such a child process is a copy of the parent process .Swoole The core high concurrency implementation of is actually based on this form of multiprocess , We'll talk about it later .
about CPU Come on , It will use polling or other scheduling algorithms to constantly execute different processes in time slices , So different processes will switch to each other . If you listen to songs , Look at the webpage , It's written in code , It seems to be going on at the same time , Actually CPU At the bottom, these processes are constantly switched and executed , It's just that the speed is too fast for you to feel . The operating system is mainly responsible for the management of these processes 、 Dispatch 、 Switch .
When you use PHP The command line executes a php When you file , In fact, it is also the same as opening QQ Start a PHP process , Or running a PHP Program . At this moment in ps -ef perhaps top In command , You can see the program information you are running . The process will occupy CPU and Memory And so on , According to the operation of the program , It may also produce Networks IO、 Hard disk IO, All of this , Are scheduled through the operating system . The legendary optimization is also aimed at optimizing the utilization of these resources .
Conventional PHP-FPM It is in the form of multi process , It means FastCGI Process Manager .Nginx In fact, it is also multi process , When a program in the same process has time-consuming operations , It's blocking ,Nginx Will wait , therefore , When the request volume is very large ,PHP-FPM Will be very tired . meanwhile ,PHP It's the dynamic language we talked about before , The loading process is complete overall loading , This will also bring loss of performance . Tradition PHP Cannot resist high concurrency , That's why high concurrency performance is poor .
Although there is a problem , But the process is the beginning of a program , If you've done C or Java The beginning of , There must be a main() Method is very important . Actually , stay PHP in , There is also this main() Method , It's just at the bottom C in , We just can't see . No process , The program does not exist , This is the foundation. , It is the root of the following threads and coroutines .
Multi process operation is actually to make full use of multi-core CPU The advantages of , One CPU To correspond to the operation of a process , So as to improve the execution efficiency of the process . Let's say we have Swoole Can be set in worker_num , Its recommended setting value is based on CPU The number of nuclear . similarly ,Nginx The configuration of the worker_processes It is also recommended to configure CPU The number of nuclear .
Threads
Threads , It is the smallest unit that the operating system can schedule operations . It is included in the process , Is the actual operation unit in the process . A thread refers to a single sequential control flow in a process , Multiple threads can be concurrent in one process , Each thread performs different tasks in parallel .
Let me put it this way , The process is a contractor , Thread is its worker . If there is only one contractor , And lay the floor , Brush the wall again , You can only do it step by step . If one of them has a problem , The later work will wait for the completion of the previous work , The operation process in this case is called Serial operation . This is the time , The contractor employed two workers , Let them work at the same time , One floor , One brushes the wall , Is it true that our engineering speed has improved a lot at once , This is called parallel operation .
To sum up , Thread is the younger brother of process , And you can perform some parallel operations synchronously in a process , Some complicated IO operation 、 Businesses that are easily blocked can be put into threads . Think about it , Our program execution efficiency will have a qualitative leap . however , Threads are not as beautiful as they seem , Threads compete for resources , Especially for the same resource . For example, we need to operate a file , Two threads access and modify in parallel , Then it's easy to have problems . This problem is actually very similar to us MySQL Transaction problems in .MySQL How did it work out ? With a lock , Use transaction isolation level . similarly , In the application , We can also lock . It's like Java Medium synchronized Synchronization lock . After adding the synchronization lock , The thread accessing the lock related content will be blocked , Only when the front one is released can the rear one come in and execute .
Threads are independent of each other , But they can share the resources of the process , There is no way to share resources among multiple processes , Only with the help of external forces or interprocess communication . In fact, this is also very easy to understand , Thread is the younger brother of process , Threads in the same process can get the information of big brother . meanwhile , Threads also consume system resources , Too many threads are the same as too many processes , Give Way CPU 、 Memory And other resources are very hi .
The English name of thread is Thread , stay Java in , You can directly instantiate an object with such a name to perform thread operations . But in PHP in , I guess you haven't seen it . Actually , stay PHP in , There is also a pthreads Expand , There is one in this extension Thread Class can use . however ,pthreads The extension has stopped maintenance . stay PHP7.2 And then there was a parallel Extensions can replace pthreads Expand . Let's talk more about this expansion later , After all, there is no ready-made information , And the documents are all in English .
stay Swoole in , In fact, we can't create threads .Swoole There will be a series of threading capabilities by default , But it is used in the underlying processing network IO And so on . Including the asynchronous tasks we talked about before , In fact, it is just sub process and asynchronous IO Application of process , It's not a thread . stay Swoole in , What we use more is actually what we want to talk about below coroutines .
coroutines
coroutines , Officially speaking , Neither process nor thread , It is more like a function call with no return value . however , If it's more popular , It's not a problem if you think of it as a thread , It's just that this thread is user mode . What does that mean ? Processes and threads are controlled by the system , Including switching scheduling , And the collaborative process can be operated by itself , No operating system involvement required , The cost of creating destruction is very low . But at the same time , It's not like multithreading can make full use of CPU . stay Swoole in , We need to make use of multi-core with the help of multi-process model in the cooperation process CPU The advantages of .
Come back , A coroutine is a lighter thread , Or let's further say that a coroutine is the younger brother of a thread . The more thread processes open , The more resources are used , The operating system brings more switching consumption . And the coroutine runs on the thread , When a collaboration process is completed , Give up voluntarily , Let another coroutine run on top of the current thread , Reduce thread switching . Empathy , We don't need to open so many threads . Be careful , The synergy here is Concurrent , It's not what the above thread said parallel . Parallelism can really run together at the same time , Concurrency is started together , But still rely on CPU Quickly switch to execute , It's still serial in nature , It just looks like it's being executed at the same time . about parallel and Concurrent Little friends who don't know much can check the relevant information in detail .
For example , So we need to drive 1 A process ,100 Threads , Now use the synergy , We can drive 1 A process ,100 Threads , Then run on each thread 100 Collaborators cheng . Now? , You are equivalent to 10000 A little brother dealing with affairs is working , Have a good time . The main thing is , The machine configuration does not need to be changed , Concurrent synchronization from 100 Turned into 10000 .
Of course , It's not that Xie Cheng is invincible . The coordination process is only waiting IO In order to reuse threads . A thread is waiting for time-consuming IO When operating, it will block , In fact, only threads are known to the operating system at this time , When it's blocked , The coroutine in this thread is also in blocking state . If there is no support for asynchronous calls , In fact, Xiecheng can't play any role . What is asynchronous invocation ? Namely asynchronous IO ,epoll Have you ever known ? Or say ,JavaScript The cycle of events in .
Since it's a cycle , In fact, you must also know , Let's summarize . A coroutine is just a thread , Control yourself by yourself , To enable multiple coroutines to be executed in one thread , When the previous process is blocked , Through asynchrony IO Put it there to execute , Then switch to other coroutine operations . At this time , The operating system does not need to switch or innovate new threads , Reduces thread switching time . Be careful , Only threads are truly parallel , Or two unrelated processes , And cooperation , It is not processed in parallel , In the thread , It's also in CPU Switching execution under the time slicing mechanism . A coroutine runtime in a thread , Other processes are suspended . Its switching cost is very low , And it is user controllable . Synergy and process 、 Thread is not a dimensional concept at all , As it says , It's just a function .
At present, collaborative process is a relatively popular development trend , especially Go There are also reasons for the language fire, which naturally supports collaborative processes .Swoole In fact, I have supported the cooperative process from a very early time , And most importantly , We can still use the original traditional way to write our code by using coprocessing , It greatly facilitates our business migration . We will come into contact with these later .
Three way features
Let's summarize the characteristics of these three processes . One by one .
process
It's the program we execute . There is no shared content between programs , Are their own independent memory space .
Scheduling switching is completed by the operating system , Users have no perception , There are many switching contents , Spending big , Low efficiency .
If communication is needed, it is usually through signal transmission , Or external tools .
Threads
The younger brother under the process , Multiple threads in the same process share memory .
True parallel execution , You can use CPU The number of nuclear .
Scheduling switch is smaller than process , But the same is done by the operating system , Moderate overhead and efficiency .
coroutines
Little brother of thread , But it's more like a function .
Serial running on threads , Depends on threads , And depends on asynchrony IO , without asynchronous IO Support for , It is no different from threads .
More lightweight , User mode switching , The cost is low , Very efficient .

summary
Today is all conceptual , There are also many references , Here is not a list , Anyway, it's Baidu , In addition, it also includes some I have learned before Harbin Institute of technology operating system Li Zhi jun Some notes from the professor's class . You can learn about it , There are many good resources in Mu classes in Chinese universities . I have always said before , operating system 、 data structure 、 The Internet 、 Design patterns Four pieces are the four magic weapons of our programmers , Not to mention becoming a great God , But at least understand . otherwise , Your progress will be slow , It's also very limited .
in addition , It's like the beginning , My level is limited , Anything wrong , Please also leave a message to correct , The revised content will also be republished to my blog at any time , Those who need the latest information can go to the blog , There are indeed updates , Wechat will also revise in the message room , So as not to mislead others .
边栏推荐
- 2022 mobile crane driver test questions simulation test platform operation
- MySQL - 函数及约束命令
- NFT数字藏品系统开发:同道大叔首推祈福系列数字藏品开售即罄
- 【MySQL从入门到精通】【高级篇】(八)聚簇索引&非聚簇索引&联合索引
- Simulated 100 questions and simulated examination of refrigeration and air conditioning equipment operation examination in 2022
- 此章节用于补充3
- NFT数字藏品开发:数字藏品助力企业发展
- Redis learning notes-2. Use of the client
- 销量下滑,品牌边缘化,失去“安全牌”的沃尔沃,还能走多远?
- Database expansion can also be so smooth, MySQL 100 billion level data production environment expansion practice
猜你喜欢

微软默默给 curl 捐赠一万美元,半年后才通知

2022 chemical automation control instrument test question simulation test platform operation

JS刷题计划——链表

Brand new! Uncover the promotion route of Ali P5 Engineer ~p8 architect

JS uses readLine to realize terminal input data

NFT digital collection development: digital collections help enterprise development

Learn UML system modeling from me

NFT数字藏品系统开发:上线即售罄,网民“秒杀”数字藏品

JS刷题计划——数组

MySQL - 多表查询与案例详解
随机推荐
[AUTOSAR RTE] - 1-talk about RTE (run time environment)
5 best overseas substitutes for WPS Office
议程速递 | 7月27日分论坛议程一览
JS刷题计划——数组
Arrangement of information security emergency plan
JS question brushing plan - array
ALV screen input option learning
js map使用
File upload and download test point
Multi thread learning notes -1.cas
Test cases of common functions
简述MES系统的11大核心功能模块
SMMU carding
Kubectl common commands and simple explanations
Tensor Rt的int8量化原理
Data security knowledge system
2022 mobile crane driver test questions simulation test platform operation
【AUTOSAR-RTE】-1-聊一聊RTE(Run-Time Environment)
【考研词汇训练营】Day 13 —— reliance,expert,subject,unconscious,photograph,exaggeration,counteract
这场竞赛,能读懂题目的你大有可为