[python] Basic use of multithreading_thread package

There are two ways to use threads in Python: functions or wrapping thread objects with classes.

Functional style: call the start_new_thread() function in the _thread module to generate a new thread. The syntax is as follows:
_thread.start_new_thread ( function, args[, kwargs] )

Parameter description:
function - thread function.
args - the arguments passed to the thread function, it must be a tuple type.
kwargs - optional arguments.

Simple example:

import _thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 无法启动线程")

while 1:
   pass

insert image description here

thread module

Python3 provides support for threads through two standard libraries _thread and threading.
_thread provides low-level, primitive threads and a simple lock, which has limited functionality compared to the threading module.

In addition to all the methods in the _thread module, the threading module also provides other methods:

threading.currentThread(): Returns the current thread variable.
threading.enumerate(): Returns a list of running threads. Running refers to a thread after it starts and before it ends, excluding threads before it starts and after it terminates.
threading.activeCount(): Returns the number of running threads, has the same result as len(threading.enumerate()).
In addition to using methods, the thread module also provides the Thread class to handle threads. The Thread class provides the following methods:
run(): A method used to represent thread activity.
start(): Start thread activity.
join([time]): Wait until the thread terminates. This blocks the calling thread until the thread's join() method is called to abort - exit normally or throw an unhandled exception - or an optional timeout occurs.
isAlive(): Returns whether the thread is alive.
getName(): Returns the thread name.
setName(): Set the thread name.

Now let's use the higher-level threadingpackage.

Create threads using the threading module

We can create a new subclass by directly inheriting from threading.Thread, and call the start() method to start a new thread after instantiation, that is, it calls the thread's run() method:

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.delay, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        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()
thread1.join()
thread2.join()
print ("退出主线程")

insert image description here

·

Reference:
https://www.runoob.com/python3/python3-multithreading.html

Guess you like

Origin blog.csdn.net/weixin_42468475/article/details/128943315