1. 启动新线程
为了便于理解,想象程序的执行就像把手指放在一行代码上,然后移动到下一行,或是流控制语句让它去的任何地方。
单线程程序只有一个“手指”。但多线程的程序有多个“手指”。每个“手指”仍然移动到控制流语句定义的下一行代码,但这些“手指”可以在程序的不同地方,同时执行不同的代码行。
Python 程序在默认情况下,只有一个执行线程。
要得到单独的线程,首先要调用 threading.Thread()函数,生成一个 Thread 对象:
import threading
import time
print("start the code")
def takeanother():
time.sleep(5)
print("I'm in a new thread, and wake up after 5 seconds")
threadObj = threading.Thread(target=takeanother) # 创建Thread对象
threadObj.start() # 启动新创建的线程
print("end of the code")
创建Thread对象时需要传递在新的线程中执行的代码,用target参数指定。在调用start()之后新的线程就会开始执行指定的代码。
2. 传递参数
你可能发现一个问题,target参数只能指定需要运行的代码,但是无法指定参数(毕竟不是每个函数都不需要参数的)。因此在创建某些Thread时,我们需要将需要的参数以其传递给新的线程。
传递参数有两种方式
- args参数列表: 可以按照函数形参的顺序传递参数,顺序无法改变
- kwargs参数字典: 按照key=value的形式指定函数某个形参对应的值,不必关心顺序
Example:
def takeanother(name):
time.sleep(5)
print("I'm in a new thread, and wake up after 5 seconds.")
print('hello ' + name)
threadObj = threading.Thread(target=takeanother, args=["Barret"]) # 创建Thread对象,传递函数需要的参数
threadObj.start() # 启动新创建的线程
# 或
threadObj = threading.Thread(target=takeanother, kwargs={'name' : 'Barret'}) # 创建Thread对象,传递函数需要的参数