


In-depth understanding of Python's processes and threads in the previous article
python video tutorial column introduces processes and threads.
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?
CPU
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.
Process
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 (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.
The use of threads and processes in Python
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
Thread
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!

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment