Process and thread are basic concepts in the operating system. There are some advantages, disadvantages and differences between them. So how to use process in Python? and thread?
The core of the computer is the CPU, which undertakes all computing tasks of the computer. The CPU is like a factory, running all the time, while the operating system manages the computer and is responsible for task scheduling. , allocation and management of resources.
A process refers to a basic unit that can run independently in the system and is used as a basic unit for resource allocation. It is composed of a set of machine instructions, data and stacks, etc. It is a process that can run independently. activity entity.
When we open our computer, we will see processes and threads. Click My Computer to see the CPU operations.
As shown in the figure, the CPU is running a total of 190 processes and 2620 threads. For example, when we click QQ again and log in to another account, another QQ process will be opened.
So, if you want to log in to multiple WeChat on your computer. Just find your WeChat shortcut, right-click to view properties, and copy the link in the target; create a new notepad, give it a random name, double-click to open it, and enter start ""
(note the quotation marks) in English, with spaces before and after), paste the link you just copied (that is, the path to the WeChat installation); then copy the entire line, and paste a few lines if you want to open as many WeChat accounts as possible; save the file and change the suffix to bat. Just double-click to run.
Thread (Thread) is also called a lightweight process. It is the smallest unit that the operating system can perform calculation scheduling. It is included in the process. , is the actual operating unit in the process.
I remember the blog written by Ruan Yifeng: Assume that the power in the factory is limited and can only be supplied to one workshop at a time. In other words, when one workshop starts working, other workshops must stop working. The meaning behind it is that a single CPU can only run one task at a time.
#A process is like a factory floor, it represents a single task that the CPU can handle. At any time, the CPU is always running one process, and other processes are in a non-running state.
Threads are like workers in a workshop. A process can include multiple threads that work together to complete a task.
In summary: A program can contain multiple processes, and multiple processes execute concurrently and are independent of each other. Therefore, a process is also the basic unit of resource allocation and scheduling in the system. Technically speaking: a process is an instance of a program when it is executed. A thread is the smallest execution unit, and a process consists of at least one thread. How processes and threads are scheduled is entirely determined by the operating system.
Now let’s talk about the use of threads and processes in Python.
In Python, support for threads is provided through the two standard libraries thread
and Threading
, threading
supports thread
Encapsulated. The threading
module provides Thread
, Lock
, RLOCK
, Condition
and other components
The use of threads and processes in Python is through the Thread class. This class is in our _thread
and threading
modules. We generally import through threading
.
By default, as long as there is no error in the interpreter, the thread is available.
>> from threading import Thread复制代码
The following are common parameter descriptions and instance methods of the Thread class.
Let’s look at a standard multi-threading example in the official documentation.
import threading import time # 定义线程要运行的函数 def func(name): # 为了便于观察,睡眠2秒 time.sleep(2) print("My name is %s\t" % name) # 创建第一个线程的实例,args参数是一个元组,后面必须加逗号分隔 t1 = threading.Thread(target=func, args=("Runsen",)) # 创建第二个线程的实例 t2 = threading.Thread(target=func, args=("Maoli",)) t1.start() t2.start() # 先打印线程名 print(t1.getName()) print(t2.getName())复制代码
Since the two threads are running at the same time, the result of print
does not have a new line.
# Below I wrote the following code to deepen the use of the threading module.
# -*- coding:utf-8 -*-# time :2019/4/9 21:52# author: Runsenimport threadingimport timedef fun1(): print('hello') time.sleep(2) print('Bye')def fun2(): print('hi') time.sleep(2) print('OUT') t1 = threading.Thread(target=fun1) t2 = threading.Thread(target=fun2) t1.start() t2.start()# t1.join()# t2.join()print('主线程完毕')复制代码
The following is the output.
hello hi 主线程完毕 Bye OUT复制代码
我们先不加join()
来阻塞,t1
和t2
两个线程同时执行,由于位置关系先打印hello
,再打印hi
,这个时候都sleep2秒钟,但是它sleep2秒钟,主程序还是在执行,所以下面打印print('主线程完毕')
,最后才打印Bye
和OUT
。
在多线程中,所有变量对于所有线程都是共享的,因此,线程之间共享数据的最大危险在于多个线程同时修改一个变量,那就乱套了,所以我们需要互斥锁,来锁住数据。
代码如上图所示,上面代码中打印的a是1还是2?
答案是:2。因为出现了global
关键字,线程间变量的共享,在func
函数中的a
是全局变量。因此在函数中a的值发生了变化。
下面,我们提高一点点难度,代码如下图所示,还是猜一猜a是啥东西。注意:这里出现了join来阻塞,并且增加了加和减的操作。
相信很多人都认为是0,其实这个a的值是变化的,可能这次是0 ,下次是1,还有可能是1000000
,比如,我可以
a就是在[-1000000,1000000]
中的一个随机数。
为什么呢?这是因为虽然他们是同时运行的,但是同时在修改我们的a,那就乱了。a在for i in range(1000000)
,就是遍历了1000000
,incr
和decr
的方法都加上一起了,在这1000000
次遍历中,不知道有多少加,多少减,比如,我1000000都是加,没有减,a就是1000000,但是这种情况的概率很低。
如果你就是想出现0,其实只需要加一个互斥锁就可以了。这样你加多少次,我就减多少次,加减的次数不会叠加。因此来了lock的用法,具体代码如下图所示。
这个a怎么运行都是 0。因为我们把这个a锁上了,这样就加1000000次,减1000000次,怎么出来都是我们的0。
相关免费学习推荐:python视频教程
The above is the detailed content of In-depth understanding of Python's processes and threads in the previous article. For more information, please follow other related articles on the PHP Chinese website!