search
HomeBackend DevelopmentPython TutorialPython multi-threaded programming 1

Python multi-threaded programming 1

Oct 18, 2016 am 11:43 AM
pythonMultithreadingprogramming

There are some basic concepts that must be understood in multi-threaded programming, which apply to all programming languages. Content:

Concurrent programming

Multi-tasking operating system

Multi-threading vs multi-process

Thread safety

Life cycle of threads

Types of threads

Concurrent programming

Different programming paradigms have different effects on software perspective. Concurrent programming regards software as a combination of tasks and resources - tasks compete and share resources, execute tasks when resources are satisfied, otherwise wait for resources.

Concurrent programming makes software easy to understand and reuse, and can greatly improve performance in certain scenarios.

Multi-tasking operating system

To achieve concurrency, you first need the support of the operating system. Most of today's operating systems are multi-tasking operating systems that can perform multiple tasks "simultaneously".

Multi-tasking can be performed at the process or thread level.

A process refers to an application running in memory. Each process has its own independent memory space. A multitasking operating system can execute these processes "concurrently".

Threads refer to code blocks that are out of order and executed multiple times in a process. Multiple threads can run "simultaneously", so multiple threads are considered "concurrent". The purpose of multi-threading is to maximize the use of CPU resources. For example, in a JVM process, all program codes run in threads.

The "simultaneity" and "concurrency" here are just a macro feeling. In fact, from a micro level, it is just the rotation execution of processes/threads, but the switching time is very short, so it creates a "parallel" feeling. .

Multi-threading vs. multi-process

The operating system will allocate a different memory block to each process, and multiple threads share the memory block of the process. The most direct difference this brings is that the cost of creating a thread is much less than the cost of creating a process.

At the same time, communication between processes is relatively difficult due to different memory blocks. It is necessary to use pipe/named pipe, signal, message queue, shared memory, socket and other means; and the communication between threads is simple and fast, which is to share the global variables in the process.

However, the operating system is responsible for process scheduling, and thread scheduling needs to be considered by ourselves to avoid deadlock, starvation, livelock, resource exhaustion, etc., which will add a certain amount of complexity. Moreover, since memory is shared between threads, we also need to consider thread safety issues.

Thread safety

Threads share global variables in the process, so when other threads change the shared variables, it may have an impact on this thread. The so-called thread safety constraint means that when a function is called repeatedly by multiple concurrent threads, it must always produce correct results. To ensure thread safety, the main method is to ensure correct access to shared variables through locking.

A stricter constraint than thread safety is "reentrancy", that is, the function is suspended during execution in one thread, and then called in another thread, and then returns to the original thread to continue execution. Proper execution is guaranteed throughout the entire process. Reentrancy is guaranteed, usually by making local copies of global variables.

Thread life cycle

The so-called xx life cycle is actually a state diagram including the creation and destruction of an object. The life cycle of the thread is shown in the figure below:

The description of each status is as follows:

New. After the newly created thread is initialized, it enters the Runnable state.

Runnable ready. Waiting for thread scheduling. Enter the running state after scheduling.

Running.

Blocked. Pause the operation, unblock and enter the Runnable state to wait for scheduling again.

Dead. The thread method returns or terminates abnormally after execution.

There may be 3 situations when entering Blocked from Running:

Synchronization: When a thread acquires a synchronization lock, but the resource is already locked by other threads, it enters the Locked state until the resource is available (the order of acquisition is controlled by the Lock queue)

Sleep: After the thread runs the sleep() or join() method, the thread enters the Sleeping state. The difference is that sleep waits for a fixed time, while join waits for the child thread to finish executing. Of course, join can also specify a "timeout period". Semantically speaking, if two threads a and b call b.join() in a, it is equivalent to merging (join) into one thread. The most common situation is to join all child threads in the main thread.

Waiting: After executing the wait() method in the thread, the thread enters the Waiting state and waits for notification from other threads.

Types of threads

Main thread: When a program starts, a process is created by the operating system (OS), and at the same time a thread runs immediately. This thread is usually called the main thread of the program (Main Thread). Every process has at least one main thread, and the main thread usually shuts down last.

Sub-threads: Other threads created in the program are sub-threads of this main thread relative to the main thread.

Daemon thread: daemon thread, an identification of a thread. Daemon threads provide services to other threads, such as the JVM's garbage collection thread. When all daemon threads are left, the process exits.

Foreground thread: Other threads relative to the daemon thread are called foreground threads.


Python’s support for multi-threading

Virtual machine level

The Python virtual machine uses GIL (Global Interpreter Lock, global interpreter lock) to mutually exclude threads from accessing shared resources, and is temporarily unable to take advantage of multi-processors.

Language level

At the language level, Python provides good support for multi-threading. Multi-threading-related modules in Python include: thread, threading, and Queue. It can easily support features such as thread creation, mutex locks, semaphores, and synchronization.

thread: The underlying support module for multi-threading, generally not recommended.

threading: Encapsulates thread, objectifies some thread operations, and provides the following classes:

Thread thread class

Timer is similar to Thread, but it has to wait for a period of time before starting to run

Lock lock primitive

RLock is a reentrant lock. Allows a single thread to reacquire an already acquired lock

Condition condition variable, which can make a thread stop and wait for other threads to meet a certain "condition"

Event General condition variable. Multiple threads can wait for an event to occur. After the event occurs, all threads are activated

Semaphore provides a "waiting room"-like structure for threads waiting for locks

BoundedSemaphore is similar to semaphore, but is not allowed to exceed the initial Value

Queue: Implements a multi-producer (Producer) and multi-consumer (Consumer) queue, supports lock primitives, and can provide good synchronization support between multiple threads. Provided classes:

Queue queue

LifoQueue last-in-first-out (LIFO) queue

PriorityQueue priority queue

The Thread class is your main thread class and can create process instances. The functions provided by this class include:

getName(self) Returns the name of the thread

isAlive(self) Boolean flag indicating whether this thread is still running

isDaemon(self) Returns the daemon flag of the thread

join(self , timeout=None) The program hangs until the thread ends. If a timeout is given, it will block for up to timeout seconds

run(self) Define the function function of the thread

setDaemon(self, daemonic) Set the daemon flag of the thread to daemonic

setName(self, name) Set the name of the thread

start(self) Start thread execution

Third-party support

If you particularly care about performance, you can also consider some "micro-thread" implementations:

Stackless Python: An enhanced version of Python that provides support for microthreads. Microthreads are lightweight threads that take more time to switch between multiple threads and occupy less resources.

greenlet: A by-product of Stackless, which calls micro-threads "tasklets". Tasklets run in pseudo-concurrency and use channels for synchronous data exchange. And "greenlet" is a more primitive concept of micro-threads without scheduling. You can construct a micro-thread scheduler yourself, or you can use greenlets to implement advanced control flow.

In the next section, we will start creating and starting threads in python.


Statement
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
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment