MST
星途 面试题库

面试题:Python中thread模块与threading模块在创建线程方式上有何不同

请详细阐述Python中thread模块与threading模块在创建线程的具体方式,并举例说明。同时,说明这种创建方式差异对实际应用可能产生的影响。
39.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

thread模块创建线程方式

thread模块是Python早期的线程模块,现已不推荐使用。其创建线程主要通过start_new_thread()函数。

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: unable to start thread")

while 1:
    pass

在此例中,start_new_thread函数第一个参数是线程函数,后续参数以元组形式传入线程函数。

threading模块创建线程方式

threading模块是Python推荐的线程模块。它有两种创建线程的方式:

  1. 继承Thread
import threading
import time

class MyThread(threading.Thread):
    def __init__(self, threadName, delay):
        threading.Thread.__init__(self)
        self.threadName = threadName
        self.delay = delay

    def run(self):
        print("Starting " + self.threadName)
        print_time(self.threadName, self.delay)
        print("Exiting " + self.threadName)

def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s: %s" % (threadName, time.ctime(time.time())))

thread1 = MyThread("Thread-1", 2)
thread2 = MyThread("Thread-2", 4)

thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("Exiting Main Thread")
  1. 实例化Thread类并传入函数
import threading
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())))

thread1 = threading.Thread(target=print_time, args=("Thread-1", 2,))
thread2 = threading.Thread(target=print_time, args=("Thread-2", 4,))

thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("Exiting Main Thread")

创建方式差异对实际应用的影响

  1. 代码结构与可读性threading模块的面向对象方式(继承Thread类)使代码结构更清晰,适合复杂逻辑的线程任务。而thread模块的函数式创建方式较为简单直接,适用于简单场景,但随着线程逻辑复杂,代码可读性会变差。
  2. 功能完整性threading模块提供了更多的功能,如线程同步工具(锁、信号量等),线程生命周期管理(join方法等)。thread模块功能相对匮乏,在处理复杂多线程场景时需要额外编写代码实现同步等功能。
  3. 维护与扩展性threading模块的设计更易于维护和扩展,新功能的添加可以通过继承或实例化Thread类的方式实现。thread模块由于其简单的函数式设计,在项目扩展时可能需要较大的代码调整。