Python多线程编程的两种方式

Python中若是要使用线程的话,python的lib中提供了两种方式。一种是函数式,一种是用类来包装的线程对象。(例子已经稍加修改)python

一、调用thread模块中的start_new_thread()函数来产生新的线程,请看代码:编程

 

Python语言 临时自用代码
import  time
import  thread
import  sys

TIMEOUT  =  20

def  myThread( no ,  interval ):
     timeTotal  =  0
     while  True :
         if  timeTotal  <  TIMEOUT :
             print  "Thread( %d ): timeTotal( %d) \n " %( no ,  timeTotal)
             timeTotal  +=  interval
         else :
             print  "Thread( %d ) exits! \n " % no
             break

def  test ():
     thread . start_new_thread( myThread , ( 1 ,  2))
     thread . start_new_thread( myThread , ( 2 ,  3))

if  __name__  ==  '__main__' :
     test()

 

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

二、经过调用threading模块继承threading.Thread类来包装一个线程对象。请看代码函数

 

Python语言 临时自用代码
import  threading
import  time

class  MyThread( threading . Thread ):
     def  __init__( self ,  no ,  interval ):
         threading . Thread . __init__( self)
         self . no  =  no
         self . interval  =  interval

     def  run( self ):
         while  self . interval  >  0 :
             print  "ThreadObject( %d ) : total time( %d) \n " %( self . no ,  self . interval)
             time . sleep( 1)
             self . interval  -=  1
def  test ():
     thread1  =  MyThread( 1 ,  10)
     thread2  =  MyThread( 2 ,  20)
     thread1 . start()
     thread2 . start()
     thread1 . join()
     thread2 . join()

if  __name__  ==  '__main__' :
     test()

 

其实thread和threading的模块中还包含了其余的不少关于多线程编程的东西,例如锁、定时器、得到激活线程列表等等,请你们仔细参考 python的文档!spa

相关文章
相关标签/搜索