向线程函数传递参数
代码
导入_thread模块
import _thread
声明thread函数
将指定其接收两个输入参数,第一个参数是线程函数描述,第二个参数是一个计数器。
def threadFunction(description, count):
## Thread function code
循环
循环的迭代次数等于线程函数的第二个参数(计数器值)。
def threadFunction(description, count):
print(description)
i = 0
while i < count:
print("Iteration: " + str(i) )
i=i+1
启动线程
thread模块的start_new_thread函数,以启动线程。第一个参数接收的是我们之前定义的线程函数,第二个参数则是一个包含函数参数的元组。
即元组的第一个元素是一个描述字符串,第二个元素则是一个计数器。
_thread.start_new_thread(threadFunction, ("Thread test function", 5))
如将计数器设为5,表示循环共有5次迭代。
总
import _thread
def threadFunction(description, count):
print(description)
i = 0
while i < count:
print("Iteration: " + str(i) )
i=i+1
_thread.start_new_thread(threadFunction, ("Thread test function", 5))
线程描述字符串以及循环每次迭代的输出。
正如预料,线程函数执行了5次循环迭代,每次迭代打印一条消息。
创建线程
代码
周期性地打印“hello world”消息。
导入模块
导入thread模块,以便使用创建线程有关的函数。
注意,模块名为_thread(一定要输入下划线)。
还需要导入time模块,以便通过调用sleep函数在函数中引入延时。
import _thread
import time
定义新建线程中执行的函数
def testThread():
while True:
print("Hello from thread")
time.sleep(2)
启动线程
_thread.start_new_thread(testThread, ())
第一个参数是之前定义的函数,第二个参数是对应于线程函数参数的元组。
空元组可通过空括号进行声明[2]
总
import _thread#创建线程有关的函数
import time#延时
def testThread():#定义新建线程中执行的函数
while True:
print("Hello from thread")
time.sleep(2)#延时两秒
_thread.start_new_thread(testThread, ())#启动线程