Python多线程之_thread与threading模块

Python 多线程之_thread threading 模块

Python 程序中,多线程的应用程序会创建一个函数,来执行需要重复执行多次的程序代码,然后创建一个线程执行该函数。一个线程是一个应用程序单元,用于在后台并行执行多个耗时的动作。

在多线程的应用程序中,每一个线程的执行时间等于应用程序所花的CPU 时间除以线程的数目。因为线程彼此之间会分享数据,所以在更新数据之前,必须先将程序代码锁定,如此所有的线程才能同步。

Python 程序至少有一个线程,这就是主线程,程序在启动后由Python 解释器负责创建主线程,在程序结束后由Python 解释器负责停止主线程。

在多线程中,主线程负责其他线程的启动、挂起、停止等操作。其他线程被称为子线程。Python 提供了两个多线程模块,即_thread threading _thread 模块提供低级的接口,用于支持小型的进程线程;threading 模块则以thread 模块为基础,提供高+级的接口。推荐使用threading 模块。

除了_thread 模块与threading 模块之外,早期Python 版本还有一个queue 模块。queue 模块内的queue 类可以在多个线程中安全地移动Python 对象。在Python 3 中,thread 模块已被废弃,用户可以使用threading 模块代替。所以,在Python 3 中不能再使用thread 模块。为了兼容性,Python 3 thread 重命名为_thread

_thread 模块


Python 中使用线程的方式有两种:函数或者用类来包装线程对象。例如调用_thread 模块中的start_new_thread() 函数来产生新线程。其语法如下:

_thread.start_new_thread ( function, args[, kwargs] )

该函数的参数如下:

1 function :线程的函数名称。

2 args :传递给线程函数的参数,必须是元组类型。

3 kwargs :关键字参数,是可选参数。

_thread 模块中其他的函数如下:

1 _thread.allocate_lock() :创建并返回一个lckobj 对象。lckobj 对象有以下3 个方法:

l   lckobj.acquire([flag]) :用来捕获一个lock

l   lcjobj.release() :释放lock

l   lckobj.locked() :若对象成功锁定,则返回True ;否则返回False

2 _thread.exit() :拋出一个SystemExit ,以终止线程的执行。它与sys.exit() 函数相同。

3 _thread.get_ident() :读取目前线程的识别码。

【例15.1 】使用_thread 模块创建多线程(源代码\ch15\15.1.py

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, ("线程1", 2, ) )
   _thread.start_new_thread( print_time, ("线程2", 4, ) )
except:
   print ("Error: 无法启动线程")
 
while 1:
   pass

保存并运行程序,输出结果如下:

线程1: Wed Jan  5 11:51:45 2022
线程2: Wed Jan  5 11:51:47 2022
线程1: Wed Jan  5 11:51:48 2022
线程1: Wed Jan  5 11:51:50 2022
线程2: Wed Jan  5 11:51:51 2022
线程1: Wed Jan  5 11:51:52 2022
线程1: Wed Jan  5 11:51:54 2022
线程2: Wed Jan  5 11:51:56 2022
线程2: Wed Jan  5 11:52:00 2022
线程2: Wed Jan  5 11:52:04 2022

执行以上线程后可以按组合键Ctrl+C 退出。

模块


threading 模块的函数如下:

1 threading.activeCount() :返回活动中的线程对象数目。

2 threading.currentThread() :返回目前控制中的线程对象。

3 threading.enumerate() :返回活动中的线程对象列表。

每一个threading.Thread 类对象都有以下方法:

1 threadobj.start() :执行run() 方法。

2 threadobj.run() :此方法被start() 方法调用。

3 threadobj.join([timeout]) :此方法等待线程结束。timeout 的单位是秒。

4 threadobj.isAlive () :返回线程是否是活动的。

5 threadobj.getName() :返回线程名。

6 threadobj.setName() :设置线程名。

下面的示例直接从threading.Thread 类继承创建一个新的子类,并实例化后调用start() 方法启动新线程,即它调用了线程的run() 方法。

【例15.2 】使用threading 模块创建多线程(源代码\ch15\15.2.py )。

import threading
import time
 
exitFlag = 0
 
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 ("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出线程:" + self.name)
 
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
 
# 创建新线程
thread1 = myThread(1, "线程1", 1)
thread2 = myThread(2, "线程2", 2)
 
# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")

保存并运行程序,输出结果如下:

开始线程:线程1开始线程:线程2
 
线程1: Wed Jan  5 12:02:38 2022
线程2: Wed Jan  5 12:02:39 2022线程1: Wed Jan  5 12:02:39 2022
 
线程1: Wed Jan  5 12:02:40 2022
线程2: Wed Jan  5 12:02:41 2022线程1: Wed Jan  5 12:02:41 2022
 
线程1: Wed Jan  5 12:02:42 2022
退出线程:线程1
线程2: Wed Jan  5 12:02:43 2022
线程2: Wed Jan  5 12:02:45 2022
线程2: Wed Jan  5 12:02:47 2022
退出线程:线程2
退出主线程

 

本文节选自《 Python 编程从零开始学(视频教学版) 》,内容发布获得作者和出版社授权。

 


 


请使用浏览器的分享功能分享到微信等