Python的Threading模块Thread类创建线程的三种常用方法

使用Threading模块中的Thread类创建线程:

1、创建Thread的实例,传给它一个函数。

# -*-coding: utf-8 -*-
#filename:mtsleepC.py
import threading
from time import sleep, ctime

loops = [4, 2]

def loop(nloop, nsec):
	print 'start loop', nloop, 'at:', ctime()
	sleep(nsec)
	print 'loop', nloop, 'done at:', ctime()

def main():
	print 'starting at:', ctime()
	threads = []
	nloops = range(len(loops))

	for i in nloops:
		t = threading.Thread(target = loop, args = (i, loops[i]))
		threads.append(t)

	for i in nloops:
		threads[i].start()

	for i in nloops:
		threads[i].join()

	print 'all DONE at:', ctime()

if __name__ == '__main__':
	main()
<span style="color:#ff0000">t = threading.Thread(target = loop, args = (i, loops[i]))</span>

此语句创建一个Thread实例,传递给它一个函数;

join方法使主线程等待子线程执行完毕;

2、创建Thread的实例,传给它一个可调用的类实例。

# -*- coding: utf-8 -*-
#filename: mtsleepD.py
import threading
from time import sleep, ctime

loops = [4, 2]

class ThreadFun(object):
	"""docstring for ThreadFun"""
	def __init__(self, func, args, name=''):
#		super(ThreadFun, self).__init__()
		self.name = name
		self.func = func
		self.args = args

	def __call__(self):
		self.func(*self.args)

def loop(nloop, nsec):
	print 'start loop', nloop, 'at:', ctime()
	sleep(nsec)
	print 'loop', nloop, 'done at:', ctime()

def main():
	print 'start at:', ctime()
	threads = []
	nloops = range(len(loops))

	for i in nloops:
		t = threading.Thread(target = ThreadFun(loop, (i, loops[i]), loop.__name__))
		threads.append(t)
	for i in nloops:
		threads[i].start()
	for i in nloops:
		threads[i].join()

	print 'all DONE at:', ctime()

if __name__ == '__main__':
	main()
t = threading.Thread(target = ThreadFun(loop, (i, loops[i]), loop.__name__))

此语句创建Thread的实例,传给它一个可调用的类实例ThreadFun;

代码中实现ThreadFun的__call__()这个特殊方法。这是由于我们已经有了要用到的参数,这里就不需要再将其传递给ThreadFun的构造函数了,直接调用即可。

3、派生Thread的子类,并创建子类的实例。

# -*- coding: utf-8 -*-
# filename: mtsleepE.py
import threading
from time import ctime, sleep

loops = [2, 4]

class MyThread(threading.Thread):
	"""docstring for MyThread"""
	def __init__(self, func, args, name=''):
		super(MyThread, self).__init__()
#		threading.Thread.__init__(self)
		self.name = name
		self.func = func
		self.args = args

	def run(self):
		self.func(*self.args)

def loop(nloop, nsec):
#	print 'start loop', nloop, 'at:', ctime()
	print 'start loop', nloop, 'at:', ctime()
	sleep(nsec)
	print 'loop', nloop, 'done at:', ctime()

def main():
	print 'startting at:', ctime()
	threads = []
	nloops = range(len(loops))

	for i in nloops:
		t = MyThread(loop, (i, loops[i]), loop.__name__)
		threads.append(t)

	for i in nloops:
		threads[i].start()

	for i in nloops:
		threads[i].join()

	print 'all DONE at:', ctime()

if __name__ == '__main__':
	main()

MyThread类是我们继承了Threading.Thread类实例化出来的一个类并对这个类进行了局部修改,后面main函数中使用了三个for循环:第一个创建了线程并加入threads列表;第二个开始让线程列表中的线程同时开始执行;第三个等待各自线程执行完毕;

《Python核心编程(第三版)》中告诉我们在面向对象的接口编程更倾向使用第三种创建线程的方法。

猜你喜欢

转载自blog.csdn.net/likunshan/article/details/80727941