1、使用thread模块(不推荐)
常用函数:
‘start_new_thread(function,args,kwargs=None)’:创建一个新的线程,并运行’function(args)’
‘allocate_lock()’: 创建锁对象 Lock object
‘exit()’: 提示线程退出
Lock的函数:
‘acquire(wait=None)’: 获取lock对象或等待wait时间
‘locked()’ 获得lock返回true,否则返回false
‘release’ :释放lock
例子1:
import thread
from time import sleep,ctime
def loop0():
print ‘start loop 0"
def main():
thread.start_new_thread(loop0,())
sleep(6)
if __name__==‘__main__‘:
main()
注意:1、虽然loop0不接受参数,但’start_new_thread’中的空tuple不能够省略;
2、使用sleep,因为在主线程创建线程后,主线程会继续运行直到退出,同时杀死所有的子线程,而不做任何的检查,这也是不推荐使用thread模块的原因之一。
例子2:
import thread
from time import sleep,ctime
loops=[4,2]
def loop(nloop,nsec,lock):
print ‘start loop‘,nloop,‘at:‘,ctime()
lock.release()
def main():
print ‘starting‘
locks=[]
nloops = range(len(loops))
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‘
if __name__==‘__main__‘:
main()
多个线程间可以通过共享lock,防止资源访问的冲突
原文地址:http://blog.csdn.net/u010640235/article/details/46604381