Python线程编程是在计算机语言应用方面应用较为广泛,如果你在Python线程编程的表达式中有所疑惑时你可以浏览我们的文章,我们的文章是对其两种表达式具体的表达方式,希望大家会有所收获。

Python中如果要使用线程的话,python的lib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。举两个简单的例子希望起到抛砖引玉的作用,关于Python多线程编程的其他知识例如互斥、信号量、临界区等请参考python的文档及相关资料。

1、调用thread模块中的start_new_thread()函数来产生新的线程,

请看代码:

python 代码  


 


###thread_example.py    


 


importtime   


mportthread   


deftimer(no,interval): #自己写的线程函数    


whileTrue:    


print'Thread:(%d)Time:%s'%(no,time.ctime())    


 


time.sleep(interval)    


deftest():#使用thread.start_new_thread()来产生2个新的线程    


thread.start_new_thread(timer,(1,1))     


thread.start_new_thread(timer,(2,3))    



if__name__=='__main__':    



test()   


 

这个是thread.start_new_thread(function,args[,kwargs])函数原型,其中function参数是你将要调用的线程函数;args是讲传递给你的线程函数的参数,他必须是个tuple类型;而kwargs是可选的参数。线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出Python线程编程的目的。

2、通过调用threading模块继承threading.Thread类来包装一个线程对象。请看代码: