此代码中是否存在同步问题?

时间:2019-09-06 03:48:01

标签: python multithreading synchronization

我在4个不同的线程中对4台主机执行ping操作。我在ping答复中搜索“ bytes = 32”。如果有4个成功的搜索,那么我正在考虑该主机是活动的。我想知道此代码是否在所有情况下都能成功运行,还是需要使用Locks来同步ping代码。?

class ip_check(threading.Thread):
    def __init__ (self,ip):
        threading.Thread.__init__(self)
        self.ip = ip

    def run(self):
        ping_out = os.popen("ping "+self.ip,"r")
        count = 0
        while True:
            line = ping_out.readline()
            if not line: 
                break
            n_received = re.search("bytes=32",line)
            if n_received:
                count = count + 1

        if count == 4 :
            print(self.ip, 'Reachable')
        else :
            print(self.ip, 'Unreachable')

tharr = []
for suffix in range(1,5):
    ip = "192.168.100." + str(suffix)
    th = ip_check(ip)
    tharr.append(th)
    th.start()

for th in tharr :
    th.join()

0 个答案:

没有答案