Table of Contents
CPU
Process
Thread
The use of threads and processes in Python
线程间变量的共享
Home Backend Development Python Tutorial In-depth understanding of Python's processes and threads in the previous article

In-depth understanding of Python's processes and threads in the previous article

Nov 17, 2020 pm 04:25 PM
python process and thread

python video tutorial column introduces processes and threads.

In-depth understanding of Python's processes and threads in the previous article

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.

In-depth understanding of Python's processes and threads in the previous article

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 threadEncapsulated. 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复制代码
Copy after login

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())复制代码
Copy after login

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('主线程完毕')复制代码
Copy after login

The following is the output.

hello
hi
主线程完毕
Bye
OUT复制代码
Copy after login

我们先不加join()来阻塞,t1t2两个线程同时执行,由于位置关系先打印hello,再打印hi,这个时候都sleep2秒钟,但是它sleep2秒钟,主程序还是在执行,所以下面打印print('主线程完毕'),最后才打印ByeOUT

线程间变量的共享

在多线程中,所有变量对于所有线程都是共享的,因此,线程之间共享数据的最大危险在于多个线程同时修改一个变量,那就乱套了,所以我们需要互斥锁,来锁住数据。

代码如上图所示,上面代码中打印的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),就是遍历了1000000incrdecr的方法都加上一起了,在这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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles