关于Python的线程

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

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

    ### thread_example.py
     import time
     import thread     

    def timer(no,interval): #自己写的线程函数
         while True:
             print 'Thread :(%d) Time:%s'%(no,time.ctime())
             time.sleep(interval)

     def test():
#使用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,达到退出线程的目的。

      2、通过调用threading模块继承threading.Thread类来包装一个线程对象。请看代码
            ### threading_example.py
      import threading
      import time
 
     # 我的timer类继承自threading.Thread类
     class timer(threading.Thread):   
         # 在我重写__init__方法的时候要记得调用基类的__init__方法
         def __init__(self, no, interval): 
             threading.Thread.__init__(self)
             self.no = no
             self.interval = interval
 

        # 重写run()方法,把自己的线程函数的代码放到这里
         def run(self):                     
             while True:
             print 'Thread Object (%d), Time:%s'%(self.no, time.ctime())
             time.sleep(self.interval)
    

     def test():
         # 产生2个线程对象
         threadone = timer(1, 1)
         threadtwo = timer(2, 3)
  
         # 通过调用线程对象的.start()方法来激活线程
         threadone.start()               
         threadtwo.start()
 
     # main test
     if name__=='__main__':
          test()

其实thread和threading的模块中还包含了其他的很多关于多线程编程的东西,例如锁、定时器、获得激活线程列表等等,请大家仔细参考python的文档!另外,线程还有退出的问题,这可以有很多种解决方法, 如事件,信号通知等。

下面是一个带事件的线程:

####
import sys
import time
import thread
import threading

e1 = threading.Event()
e2 = threading.Event()

def timer1(no, interval):
    exit_count = 0
    while True:
        print 'Thread:(%d) Time:%s' % (no, time.ctime())
        time.sleep(interval)
        exit_count = exit_count + 1
        if exit_count == 10:
            e1.set()
            break
    print 'end thread -- %d' %( no, )

def timer2(no, interval):
    while True:
        print 'Thread:(%d) Time:%s' % (no, time.ctime())
        time.sleep(interval)
        if e1.isSet():
            e2.set()
            break
    print 'end thread -- %d' % ( no, )
       

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

    ## 
    e1.wait()
    e2.wait()

    print('End test.')

#
if __name__ == '__main__':
    test()

 

 

 

 

 

   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值