Home Backend Development Python Tutorial An introduction to multi-threading in Python

An introduction to multi-threading in Python

Aug 23, 2017 am 11:44 AM
python threading getting Started

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
Copy after login

Get activated Number of threads


threading.active_count()
Copy after login

View all thread information


threading.enumerate()
Copy after login

View currently running threads


threading.current_thread()
Copy after login

Add a 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()
Copy after login

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()
Copy after login

The example is shown above. When the join function is not used, the result is as shown below:

When the join function is executed, T2 will be run only after T1 has finished running, and then run print ('all done')

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 queue


 class queue.Queue(maxsize=0)
Copy after login

maxsize is an integer, Indicates the upper limit of the number of data that can be stored in the queue. When the upper limit is reached, insertion will cause blocking until the data in the queue is consumed. If maxsize is less than or equal to 0, there is no limit on the queue size

(2) LIFO queue last in first out


class queue.LifoQueue(maxsize=0)
Copy after login

(3) Priority queue


class queue.PriorityQueue(maxsize=0)
Copy after login

in the video I don’t understand the code very well


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()
Copy after login

The running result is as follows

## 1.5 GIL is not necessarily efficient


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)
Copy after login

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()
Copy after login

运行结果如下所示:

总结

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!

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)

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.

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.

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.

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 vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

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

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

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.

See all articles