#2
fall_bernana2019-11-08 15:53
回复 楼主 kfclassmate
|
脚本功能:检查一段ip地址是否可以ping通,使用了多线程
问题:在linux平台运行脚本很快执行完毕,但在mac平台运行很慢,通过在lock.acquire()获得锁和lock.release()释放锁后打印记录跟踪进程执行过程了,在mac上运行时基本上是每隔1秒打印一次,在linux平台执行时基本1秒就打印完毕了
代码
程序代码:
import threading,sys,os,re,time
inused = []
notused = []
inusedcount = 0
notusedcount = 0
lock = threading.Lock()
class ipcheck(threading.Thread):
def __init__(self,ip,cmd):
threading.Thread.__init__(self)
self.ip = ip
self.cmd = cmd
def run(self):
code = os.system(self.cmd)
global inusedcount
global notusedcount
global inused
global notused
if code == 0:
lock.acquire()
inused.append(self.ip)
inusedcount += 1
lock.release()
else:
lock.acquire()
notused.append(self.ip)
notusedcount += 1
lock.release()
inused = []
notused = []
inusedcount = 0
notusedcount = 0
lock = threading.Lock()
class ipcheck(threading.Thread):
def __init__(self,ip,cmd):
threading.Thread.__init__(self)
self.ip = ip
self.cmd = cmd
def run(self):
code = os.system(self.cmd)
global inusedcount
global notusedcount
global inused
global notused
if code == 0:
lock.acquire()
inused.append(self.ip)
inusedcount += 1
lock.release()
else:
lock.acquire()
notused.append(self.ip)
notusedcount += 1
lock.release()