Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use threads in Python

Shulou Source: shulou.com Published: 2022-06-02 06:59:18 10月30日 Update

Xiaobian to share with you how to use threads in Python, I believe most people still do not know how, so share this article for everyone's reference, I hope you have a lot of gains after reading this article, let's go to understand it together!

Threads are used in Python in two ways: as functions or by wrapping threaded objects in classes.

Functional formula:

Call the start_new_thread() function in the thread module to spawn a new thread.

The syntax is as follows: thread.start_new_thread(function, args[, kwargs]) Parameters:

function -Thread function.

args -parameter passed to thread function, it must be of tuple type.

kwargs -Optional parameters.

import threadimport time #Define a function def print_time(threadName, delay) for a thread: count = 0 while count < 5: time.sleep(delay) count += 1 print ("%s: %s" % (threadName, time.ctime(time.time()))) #Create two threads try: thread.start_new_thread(print_time, ("Thread-1", 2,)) thread.start_new_thread(print_time, ("Thread-2", 4,))except: print ("Error: unable to start thread") while 1: pass Creating threads using the Threading module

Create threads using the Thread module, inherit directly from threading.Thread, and override the__init__method and run method:

import threadingimport time exitFlag = 0 class myThread (threading.Thread): #Inherit parent threading.Thread def __init__(self, threadID, name, counter): threading.Thread.__ init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): #Write the code to be executed into the run function. After the thread is created, it will run the run function directly print ("Starting " + self.name) print_time(self.name, self.counter, 5) print ("Exiting " + self.name) def print_time(threadName, delay, counter): while counter: if exitFlag: (threading.Thread).exit() time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 #thread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2) #thread1.start()thread2.start () print ("Leaving Main Thread") thread synchronization

If multiple threads modify a certain data together, unpredictable results may occur. In order to ensure the correctness of the data, multiple threads need to be synchronized.

Simple thread synchronization can be achieved using Lock and Rlock of Thread objects, both of which have acquire and release methods, and for data that needs to be operated on by only one thread at a time, you can put its operation between acquire and release methods. As follows:

import threadingimport time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__ init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) #Get lock, return True after successfully getting lock #Optional timeout parameter will block until lock is obtained if left blank #Otherwise it will return False after timeout threadLock.acquire() print_time(self.name, self.counter, 3) Release the lock threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 threadLock = threading.Lock()threads = [] #Create a new thread thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) #Start a new threadthread1.start ()thread2.start () #Add threads to the thread list threads.append(thread1)threads.append(thread2) #Wait for all threads to complete for t in threads: t.join()print ("Exiting Main Thread") Thread Priority Queue

Python's Queue module provides synchronous, thread-safe queue classes, including FIFO (first-in, first-out) Queue, LIFO (last-in, first-out) Queue, and PriorityQueue. These queues implement lock primitives and can be used directly in multithreading. Queue can be used to achieve synchronization between threads.

Common methods in Queue module:

Queue.qsize() Returns the size of the queue

Queue.empty() Returns True if the queue is empty, False otherwise

Queue.full() Returns True if the queue is full, False otherwise

Queue.full corresponds to maxsize

Queue.get([block[, timeout]]) Get queue, timeout Wait time

Queue.get_nowait() Quite Queue.get(False)

Queue.put(item) write queue, timeout wait time

Queue.put_nowait(item) corresponds to Queue.put(item, False)

Queue.task_done() After completing a task, the Queue.task_done() function sends a signal to the queue that the task has completed

Queue.join() actually means waiting until the queue is empty before doing anything else

import Queueimport threadingimport time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__ init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print ("Starting " + self.name) process_data(self.name, self.q) print ("Exiting " + self.name) def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print ("%s processing %s" % (threadName, data)) else: queueLock.release() time.sleep(1) threadList = ["Thread-1", "Thread-2", "Thread-3"]nameList = ["One", "Two", "Three", "Four", "Five"]queueLock = threading.Lock()workQueue = Queue.Queue(10)threads = []threadID = 1 #Create a new thread for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1 #fill queue queueLock.acquire()for word in nameList: workQueue.put(word)queueLock.release() #Wait for queue to empty while not workQueue.empty(): pass #notify threads that it is time to exit exitFlag = 1 #wait for all threads to complete for t in threads: t.join()print ("Exiting Main Thread") That's all for "How to use threads in Python". Thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Threads queues functions methods modules synchronization parameters objects data articles two priority content multiple size time first out security success not so much Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft Huawei Shulou Technology Apple