Python provides several modules for multithreaded programming, including thread, threading, and queue. The thread and threading modules allow programmers to create and manage threads. The thread module provides basic thread and lock support, while threading provides a higher level of functionality for more powerful threading management. The queue module allows users to create a queue data structure that can be used to share data between multiple threads.
Note: Avoid using the thread module because it does not support daemon threads. When the main thread exits, all child threads are forcibly evicted, regardless of whether they are still working.
The following focuses on the threading module.
Our multithreading inherits the thread class in the threading module, and its main functions are:
Function description
Start () execution of the thread
Run () A function that defines the function of a thread (typically overridden by a quilt class)
The Join (Timeout=none) program hangs until the thread finishes, and if timeout is given, the maximum blocking timeout seconds
GetName () returns the name of the thread
SetName (name) sets the name of the thread
IsAlive () Boolean flag indicating whether this thread is still running
Isdaemon () returns the daemon flag of the thread
Setdaemon (daemonic) sets the thread's daemon flag to daemonic (must be called before the start () function is called)
Here is an example:
Import Threading
Import Time
class Mythread (threading. Thread):
def __init__ (self,num):
Threading. Thread.__init__ (self)
self.num = num
def run (self):
if Self.num < 2:
time.sleep (self.num);
Print Self.num
if __name__ = = ' __main__ ':
nums=[1,2,3,4,5] for
num in nums:
t = mythread (num)
T.start ()
In the main function, start 5 threads at the same time, if Num < 3, hibernate for a while, so 2,3,4,5 is first printed out, 1 is finally printed out.