面试题答案
一键面试-
thread模块创建线程基本步骤:
- 导入
thread
模块:在Python脚本开头使用import thread
语句导入该模块(注意:thread
模块在Python 3中已被_thread
取代,这里基于其旧版本说明)。 - 定义线程函数:编写一个函数,这个函数将作为线程执行的任务。
- 使用
thread.start_new_thread()
函数启动新线程:该函数接受两个参数,第一个是线程函数名,第二个是传递给线程函数的参数元组(如果没有参数则传递空元组()
)。
- 导入
-
在线程中传递参数示例:
import thread
import time
def print_time(thread_name, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print(f"{thread_name}: {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
在上述示例中,print_time
函数是线程执行的任务,thread.start_new_thread(print_time, ("Thread - 1", 2))
中,("Thread - 1", 2)
是传递给print_time
函数的参数,"Thread - 1"
对应thread_name
参数,2
对应delay
参数。同样,另一个线程也传递了不同的参数。
需再次强调,在Python 3中,建议使用_thread
模块(与thread
模块类似)或更高级的threading
模块来处理线程。例如使用threading
模块改写上述代码如下:
import threading
import time
def print_time(thread_name, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print(f"{thread_name}: {time.ctime(time.time())}")
# 创建两个线程
t1 = threading.Thread(target = print_time, args = ("Thread - 1", 2))
t2 = threading.Thread(target = print_time, args = ("Thread - 2", 4))
t1.start()
t2.start()
t1.join()
t2.join()
在threading.Thread
中,target
指定线程执行的函数,args
以元组形式传递参数给该函数。join
方法用于等待线程完成。