Python 多线程

Python 多线程

thread模块:

//thread模块函数:
 - start_new_thread(func,args,keywords)产生一个新的线程,指定函数的参数
 - allocate_lock()						分配一个locktype的锁对象
 - exit()								线程退出

// LockType类型锁对象函数:
- acquire()							尝试获取锁对象
- locked()								如果获取了锁对象返回true,否则返回false
- release()							释放锁

例子:
#!/usr/bin/env python

import thread
from time import sleep ,ctime

loops = [4,2]
def loop(nloop,nesc,lock):
	print "start loop " , nloop , "at : " , ctime()
	sleep(nesc)
	print "loop" , nloop, "done at : " ,ctime()
	lock.release()

def main():
	print "starting at : " , ctime()
	locks = []
	nloops = range(len(locks))
	
	for i in nloops:
		lock = thread.allocate_lock()
		lock.acquire()
		locks.append(lock)

	for i in nloops:
		thread.start_new_thread(loop , (i , loops[i] , locks[i]))

	for i in nloops:
		while locks[i].locked():
			pass
	
	print "all done at : " , ctime()

if __name__ == "__main__"
	main()

threading模块:

Thread可以有多种方法来创建线程:
1、创建一个Thread的实例,传给他一个函数
2、创建一个Thread的实例,传给他一个可调用的类对象
3、从Thread派生出一个子类,创建一个这个子类的实例

Thread对象的函数:
- start()				开始线程的执行
- run()					定义现场的功能的函数(一般会被子类重写)
- join(timeout=None)	程序挂起,直到线程结束;如果给了timeout,则最多阻塞timeout秒
- getName()				返回线程的名字
- setName(name)			设置线程的名字
- isAlive()				布尔标志,表示这个现场是否还在运行
- isDaemon()			返回线程的daemon标志
- setDaemon(daemon)		把线程的daemon标志设为daemonic(一定要在调用start()函数前调用)

创一个Thread的实例,传给他一个函数:
例子:
#!/usr/bin/env python

import threading
from time import sleep ,ctime

loops = [4,2]
def loop(nloop,nesc):
	print "start loop " , nloop , "at : " , ctime()
	sleep(nesc)
	print "loop" , nloop, "done at : " ,ctime()

def main():
	print "starting at : " , ctime()
	threads= []
	nloops = range(len(locks))
	
	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()

你可能感兴趣的:(python,多线程)