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