Python multi-threaded programming 1
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.

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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.

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.

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.

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.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.
