[Python]Two ways to use Threading

来源:互联网 发布:身份证注册软件下载 编辑:程序博客网 时间:2024/05/01 01:56
Python的Lib里,提供了两种使用Threading的方法:
一、函数式:
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(timer, (
11))
    thread.start_new_thread(timer, (
23))

if __name__ == '__main__':
    test()
    

 

thread.start_new_thread(function, args[, kwargs])

这个是函数原型, 其中, function是要调用的线程函数;args是传递给你的线程函数的参数,必须是Tuple类型;kwargs是可选参数。

这种线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用 thread.exit(), 抛出SystemExit exception, 达到退出线程的目的。

 

二、继承自 threading.Thread类

import threading
import time

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

    
def run(self):  
        
"重写 run() 方法,实现自己的线程函数"
        
while True:
            
print 'Thread Object (%d), Time: %s' % (self.no, time.ctime())
            time.sleep(self.interval)

def test():
    threadone 
= timer(11)
    threadtwo 
= timer(23)

    threadone.start()
    threadtwo.start()

if __name__ == '__main__':
    test()

其中, thread和threading的模块中还包含很多关于多线程编程的东西,如锁、定时器、获得激活线程列表等等。
 

原创粉丝点击