线程进程与协程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程进程与协程相关的知识,希望对你有一定的参考价值。
一、线程和进程
1.什么是进程?
一个程序的执行实例就是一个进程。An executing instance of a program is called a process.
一个进程都有一个虚拟内存地址空间,可执行代码,调用操作系统的接口,安全的上下文,唯一的进程标识符PID,环境变量,优先级类,最大最小的工作的内存空间,和最少一个线程。
每一个进程想要执行,至少需要有一个线程,经常叫做主线程;
进程中的线程可以创建额外的线程,主线程可以创建子线程,子线程又可以创建子线程。
线程之间相互独立,不相互依赖。a线程生成b线程,a线程消失,b线程仍然可以存在。
A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.
Suppose you‘re reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped.
One way to achieve that is by jotting down the page number, line number, and word number.
So your execution context for reading a book is these 3 numbers.
If you have a roommate, and she‘s using the same technique, she can take the book while you‘re not using it, and resume reading from where she stopped.
Then you can take it back, and resume it from where you were. Threads work in the same way.
A CPU is giving you the illusion that it‘s doing multiple computations at the same time.
It does that by spending a bit of time on each computation.
It can do that because it has an execution context for each computation.
Just like you can share a book with your friend, many tasks can share a CPU.
On a more technical level, an execution context (therefore a thread) consists of the values of the CPU‘s registers.
Last: threads are different from processes.
A thread is a context of execution, while a process is a bunch of resources associated with a computation.
A process can have one or many threads.
Clarification:
the resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process).
以上是关于线程进程与协程的主要内容,如果未能解决你的问题,请参考以下文章
Python:线程进程与协程——multiprocessing模块