An introduction to multi-threading in Python
Multi-threading can be simply understood as executing multiple tasks at the same time. This article will share with you a detailed example of Python multi-threading Threading beginner tutorial. Friends who are interested can learn together
1.1 What is multi-threading
Multithreading can simply be understood as executing multiple tasks at the same time.
Both multi-process and multi-threading can perform multiple tasks, and threads are part of the process. The characteristic of threads is that they can share memory and variables between threads, and consume less resources (however, in the Unix environment, the difference in resource scheduling consumption between multi-process and multi-thread is not obvious, and Unix scheduling is faster). The disadvantage is the synchronization and acceleration between threads. Locks are more troublesome.
1.2 Add thread Thread
Import module
##
import threading
threading.active_count()
threading.enumerate()
threading.current_thread()
threading.Thread()Receive parameter target represents the task to be completed by this thread, you need to define it yourself
def thread_job(): print('This is a thread of %s' % threading.current_thread()) def main(): thread = threading.Thread(target=thread_job,) # 定义线程 thread.start() # 让线程开始工作 if __name__ == '__main__': main()
1.3 join function
Because the threads are running at the same time, using the join function allows the thread to complete before proceeding to the next step, that is, blocking the calling thread. , until all tasks in the queue are processed.import threading import time def thread_job(): print('T1 start\n') for i in range(10): time.sleep(0.1) print('T1 finish\n') def T2_job(): print('T2 start\n') print('T2 finish\n') def main(): added_thread=threading.Thread(target=thread_job,name='T1') thread2=threading.Thread(target=T2_job,name='T2') added_thread.start() #added_thread.join() thread2.start() #thread2.join() print('all done\n') if __name__=='__main__': main()
1.4 Queue for storing process results
Queue is a thread-safe queue (FIFO) implementation in the Python standard library, which provides a first-in-first-out data structure suitable for multi-threaded programming. , that is, a queue, used to transfer information between producer and consumer threads (1) Basic FIFO queueclass queue.Queue(maxsize=0)
class queue.LifoQueue(maxsize=0)
class queue.PriorityQueue(maxsize=0)
import threading import time from queue import Queue def job(l,q): for i in range(len(l)): l[i]=l[i]**2 q.put(l) def multithreading(): q=Queue() threads=[] data=[[1,2,3],[3,4,5],[4,5,6],[5,6,7]] for i in range(4): t=threading.Thread(target=job,args=(data[i],q)) t.start() threads.append(t) for thread in threads: thread.join() results=[] for _ in range(4): results.append(q.get()) print(results) if __name__=='__main__': multithreading()
Global Interpreter Lock Global interpreter lock, the execution of python is controlled by the python virtual machine (also called the interpreter main loop), and the control of GIL controls the python virtual machine Access ensures that only one thread is running in the interpreter at any time. In a multi-threaded environment, the python virtual machine executes in the following manner:
1. Set up GIL
2. Switch to a thread to run
3. Run:
a. Specify the number of bytecode instructions, or
b. The thread actively gives up control (you can call time.sleep(0))
4. Set the thread For sleep state
5. Unlock GIL
6. Repeat 1-5
When calling external code (such as C/C++ extension functions), the GIL will be Locked until the end of this function (since no python bytecode is run during this period, no thread switching will be performed).
The following is the code example in the video. It expands a number by 4 times, divides it into the normal method and allocates it to 4 threads. It is found that the time consumption is not much different.
import threading from queue import Queue import copy import time def job(l, q): res = sum(l) q.put(res) def multithreading(l): q = Queue() threads = [] for i in range(4): t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i) t.start() threads.append(t) [t.join() for t in threads] total = 0 for _ in range(4): total += q.get() print(total) def normal(l): total = sum(l) print(total) if __name__ == '__main__': l = list(range(1000000)) s_t = time.time() normal(l*4) print('normal: ',time.time()-s_t) s_t = time.time() multithreading(l) print('multithreading: ', time.time()-s_t)
The running result is:
1.6 线程锁 Lock
如果线程1得到了结果,想要让线程2继续使用1的结果进行处理,则需要对1lock,等到1执行完,再开始执行线程2。一般来说对share memory即对共享内存进行加工处理时会用到lock。
import threading def job1(): global A, lock #全局变量 lock.acquire() #开始lock for i in range(10): A += 1 print('job1', A) lock.release() #释放 def job2(): global A, lock lock.acquire() for i in range(10): A += 10 print('job2', A) lock.release() if __name__ == '__main__': lock = threading.Lock() A = 0 t1 = threading.Thread(target=job1) t2 = threading.Thread(target=job2) t1.start() t2.start() t1.join() t2.join()
运行结果如下所示:
总结
The above is the detailed content of An introduction to multi-threading in Python. For more information, please follow other related articles on the PHP Chinese website!

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



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.

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.

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 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 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.

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.

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.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
