search
HomeBackend DevelopmentPython TutorialCreation and basic calling methods of multi-threading in Python

1. The role of multi-threading
In short, multi-threading is the parallel processing of independent sub-tasks, thereby greatly improving the efficiency of the entire task.

2. Multi-threading related modules and methods in Python
Python provides several modules for multi-threaded programming, including thread, threading, Queue, etc.
The thread module provides basic thread and lock support. In addition to generating threads, it also provides basic synchronization data structure lock objects, including:
start_new_thread(function, args kwargs=None) Generates a new thread to run the given function
allocate_lock() allocates a lock object of type LockType
exit() lets the thread exit
acquire(wait=None) attempts to acquire the lock object
locked() returns TRUE if the lock object is acquired, otherwise returns FALSE
release() Release the lock
threading provides higher-level, more powerful thread management functions
Thread class represents the execution object of a thread
Lock lock primitive object
RLock is a reentrant lock object, allowing a single thread to obtain the acquired lock again
The queue module allows users to create a queue data structure that can be used to share data between multiple threads
Can be used for inter-process communication to share data between threads
Module function queue(size) creates a Queue object with size size
The queue object function qsize() returns the queue size
empty() returns True if the queue is empty, otherwise returns False
put(item, block=0) Put ITEM into the queue. If block is not 0, the function will block until it is in the queue
get(block=0) takes an object from the queue. If block is given, the function will block until there is an object in the queue

3. Example
Currently, Python's lib provides two startup methods for multi-thread programming. One is the more basic start_new_thread method in the thread module, which runs a function in the thread. The other is to use the thread object Thread class of the integrated threading module. .
What is currently used is to call the start_new_thread() function in the thread module in the old version to generate a new thread
In comparison, the implementation mechanism of thread.start_new_thread(function,(args[,kwargs])) is actually more similar to C, where the function parameter is the thread function to be called; (args[,kwargs]) is the thread function to be called. Create a tuple type of parameters for the thread function, where kwargs is an optional parameter. The newly created thread generally exits automatically when the execution of the thread function ends, or calls thread.exit() in the thread function to throw a SystemExit exception to achieve the purpose of thread exit.

print "=======================thread.start_new_thread启动线程============="  
import thread  
#Python的线程sleep方法并不是在thread模块中,反而是在time模块下  
import time  
def inthread(no,interval):  
  count=0  
  while count<10:  
    print "Thread-%d,休眠间隔:%d,current Time:%s"%(no,interval,time.ctime())  
    #使当前线程休眠指定时间,interval为浮点型的秒数,不同于Java中的整形毫秒数  
    time.sleep(interval)  
    #Python不像大多数高级语言一样支持++操作符,只能用+=实现  
    count+=1  
  else:  
    print "Thread-%d is over"%no  
    #可以等待线程被PVM回收,或主动调用exit或exit_thread方法结束线程  
    thread.exit_thread()  
#使用start_new_thread函数可以简单的启动一个线程,第一个参数指定线程中执行的函数,第二个参数为元组型的传递给指定函数的参数值  
thread.start_new_thread(inthread,(1,2))  
  #线程执行时必须添加这一行,并且sleep的时间必须足够使线程结束,如本例  
  #如果休眠时间改为20,将可能会抛出异常  
time.sleep(30)  
'''  

When starting a thread using this method, exceptions may occur

Unhandled exception in thread started by 
Error in sys.excepthook: 
Original exception was: 

Solution: After starting a thread, make sure that the main thread waits for all sub-threads to return results before exiting. If the main thread ends earlier than the sub-threads, regardless of whether the sub-threads are background threads, they will be interrupted and this exception will be thrown.
If there is no response to the blocking wait, in order to prevent the main thread from exiting early, time.sleep must be called to make the main thread sleep for a long enough time. In addition, a locking mechanism can also be used to avoid similar situations. When starting the thread, give each thread A lock is added until the thread is running, and then the lock is released. At the same time, a while loop is used in Python's main thread to continuously determine that each thread lock has been released.

import thread;  
from time import sleep,ctime;  
from random import choice  
#The first param means the thread number  
#The second param means how long it sleep  
#The third param means the Lock  
def loop(nloop,sec,lock):  
  print "Thread ",nloop," start and will sleep ",sec;  
  sleep(sec);  
  print "Thread ",nloop," end ",sec;  
  lock.release();  
  
def main():  
  seconds=[4,2];  
  locks=[];  
  for i in range(len(seconds)) :  
    lock=thread.allocate_lock();  
    lock.acquire();  
    locks.append(lock);  
      
  print "main Thread begins:",ctime();  
  for i,lock in enumerate(locks):  
    thread.start_new_thread(loop,(i,choice(seconds),lock));  
  for lock in locks :  
    while lock.locked() :   
      pass;  
  print "main Thread ends:",ctime();  
  
if __name__=="__main__" :  
  main();  

Many introductions say that the Threading module is recommended in new python versions, but it has not been applied yet. . .

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之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.