Python多线程——简单示例
如果你想在一个进程里面同时作很多事情的话,线程应该是你的答案。它们能让你建立起来一系列的进程(或者子进程),每一个都可以独立运行,而且还可以归并起来或者互相协调。
在许多应用中,线程的使用有些大材小用。不过对于某些情况,它们的确很有用。
线程可以派上用场的Python应用
比如说,你想要检查网络上很多电脑的可用性的话,当然是使用ping。但是,有个问题,如果你去ping一个没有运行的主机,会一直等到超时。这样的话,如果你去检查的超多主机都没有回应的话,快速的反应时间是必须的,否则要等很久很久。
这里是顺序去ping 10个主机的Python程序:
import os
import re
import time
import sys
lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response","Alive")
print time.ctime()
for host in range(60,70):
ip = "192.168.200."+str(host)
pingaling = os.popen("ping -q -c2 "+ip,"r")
print "Testing ",ip,
sys.stdout.flush()
while 1:
line = pingaling.readline()
if not line: break
igot = re.findall(lifeline,line)
if igot:
print report[int(igot[0])]
print time.ctime()
运行它,虽然它工作正常,但是有些慢。
[trainee@buttercup trainee]$ python alive
Mon May 9 05:22:51 2005
Testing 192.168.200.60 No response
Testing 192.168.200.61 No response
Testing 192.168.200.62 No response
Testing 192.168.200.63 No response
Testing 192.168.200.64 No response
Testing 192.168.200.65 No response
Testing 192.168.200.66 Alive
Testing 192.168.200.67 No response
Testing 192.168.200.68 No response
Testing 192.168.200.69 No response
Mon May 9 05:23:19 2005
[trainee@buttercup trainee]$
用了28秒,换句话说,等一个无法到达的主机要花3秒钟。
同样的应用,用Python线程来搞
让我们来先写一下并测测看,然后再说明。
import os
import re
import time
import sys
from threading import Thread
class testit(Thread):
def __init__ (self,ip):
Thread.__init__(self)
self.ip = ip
self.status = -1
def run(self):
pingaling = os.popen("ping -q -c2 "+self.ip,"r")
while 1:
line = pingaling.readline()
if not line: break
igot = re.findall(testit.lifeline,line)
if igot:
self.status = int(igot[0])
testit.lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response","Alive")
print time.ctime()
pinglist = []
for host in range(60,70):
ip = "192.168.200."+str(host)
current = testit(ip)
pinglist.append(current)
current.start()
for pingle in pinglist:
pingle.join()
print "Status from ",pingle.ip,"is",report[pingle.status]
print time.ctime()
接下来,运行:
[trainee@buttercup trainee]$ python kicking
Mon May 9 05:23:36 2005
Status from 192.168.200.60 is No response
Status from 192.168.200.61 is No response
Status from 192.168.200.62 is No response
Status from 192.168.200.63 is No response
Status from 192.168.200.64 is No response
Status from 192.168.200.65 is No response
Status from 192.168.200.66 is Alive
Status from 192.168.200.67 is No response
Status from 192.168.200.68 is No response
Status from 192.168.200.69 is No response
Mon May 9 05:23:39 2005
[trainee@buttercup trainee]$
3秒钟!比起我们一个一个ping、一个一个等来,这个时间非常让人接受了。