python多线程编程(五)

来源:互联网 发布:皮卡刻字机端口设置 编辑:程序博客网 时间:2024/05/21 09:52

一、派生多线程。

开始时,Thread要完成一些基本初始化,然后调用其run方法,这会调用传递到构造函数的目标函数,要创建一个Thread子类,需要覆盖run()来完成所需工作。

import threadingimport loggingimport urllib2logging.basicConfig(    level = logging.DEBUG,    format = '%(levelname)s (%(threadName)s) %(message)s',)class MyThread(threading.Thread):def run(self):logging.debug('runing')logging.debug(threading.currentThread().getName())returndef test(self):return 'nihao'for i in range(6):t = MyThread()t.start()print t.test()
解释:以上代码比较简单,不解释

二、构造函数传递参数

由于传递到Thread构造函数的args和kwargs值保存在私有变量中,所以不能容易从子类访问这些值,要向一个定制的线程类型传递参数,需要重新定义构造函数,将这些值保存在子类可见的一个实例属性中。

import threadingimport loggingimport urllib2logging.basicConfig(    level = logging.DEBUG,    format = '%(levelname)s (%(threadName)s) %(message)s',)class MyThread(threading.Thread):    def __init__(self,group=None,target=None,name=None,args=(),kwargs=None,verbose=None):        threading.Thread.__init__(self,group=group,target=target,name=name,verbose=verbose)        self.args = args        self.kwargs = kwargs    def run(self):           logging.debug('running with %s and %s',                       self.args,self.kwargs)        returnfor i in range(6):    t = MyThread(args=(i,),kwargs={'a':'A','b':'B'})    t.start()
结果:

DEBUG (Thread-1) running with (0,) and {'a': 'A', 'b': 'B'}DEBUG (Thread-2) running with (1,) and {'a': 'A', 'b': 'B'}DEBUG (Thread-3) running with (2,) and {'a': 'A', 'b': 'B'}DEBUG (Thread-4) running with (3,) and {'a': 'A', 'b': 'B'}DEBUG (Thread-5) running with (4,) and {'a': 'A', 'b': 'B'}DEBUG (Thread-6) running with (5,) and {'a': 'A', 'b': 'B'}


三、定时器线程

有时出于某种原因需要派生Thread,Timer就是这样一个例子,Timer也包含在threading中。Timer在一个延迟之后开始工作,可以在这个延迟期间内任意时刻取消。

import threadingimport loggingimport timelogging.basicConfig(    level = logging.DEBUG,    format = '%(levelname)s (%(threadName)s) %(message)s',)def delay():    logging.debug('worker running')    returnt1 = threading.Timer(3,delay)t1.setName('t1')t2 = threading.Timer(3,delay)t2.setName('t2')logging.debug('starting timers')t1.start()t2.start()logging.debug('waiting befor canceling %s',t2.getName())time.sleep(2)logging.debug('canceling %s',t2.getName())t2.cancel()logging.debug('done')
结果:

DEBUG (MainThread) starting timersDEBUG (MainThread) waiting befor canceling t2DEBUG (MainThread) canceling t2DEBUG (MainThread) doneDEBUG (t1) worker running
解释:

第二个定时器永远不会运行,第一个定时器会在其余的主程序完成之后运行。大家可以把延迟时间修改,查看程序的运行情况。

(未完待续)




0 0
原创粉丝点击