用函数调用对象两次,重复字典输出

时间:2019-06-20 14:10:06

标签: python multithreading object python-multithreading

我正在尝试两次获取相同函数的输出,并间隔一定的时间,第一个输出正确,但是第二个输出从第一个输出中获取输出。

我尝试使用多线程和刷新,但是问题似乎出在Pingerson对象(或我怎么称呼它)中。由于我使用了不同的函数来调用具有不同名称的对象,因此可以解决问题,但是我正在寻找一种解释或更好的解决方案。

class Pingerson(object):
    status = {'alive': [], 'dead': []} # Se llena a medida que corre
    hosts = [] # lista de hosts a pingear

    # nº de procesos paralelos
    thread_count = 4

    # el lock evita que se sobreescriban los procesos
    lock = threading.Lock()

    def ping(self, ip):
        # pingea esperando 1
        ret = subprocess.call(['ping', '-c', '1', '-W', '1', ip],
                              stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w'))

        return ret == 0 # Return True if our ping command succeeds

    def pop_queue(self):
        ip = None

        self.lock.acquire() # agarra o espera-agarra el lock

        if self.hosts:
            ip = self.hosts.pop()

        self.lock.release() # suelta el lock asi otro thread puede agarrarlo

        return ip

    def dequeue(self):
        while True:
            ip = self.pop_queue()

            if not ip:
                return None

            result = 'alive' if self.ping(ip) else 'dead'
            self.status[result].append(ip)

    def start(self):
        threads = []

        for i in range(self.thread_count):
            # Crea self-thread_count numero de threads que juntos van a cooperar para
            # borrar cada ip de la lista
            t = threading.Thread(target=self.dequeue)
            t.start()
            threads.append(t)

        # Espera a que todos los threads hayan terminado
        # .join() bloquea hasta que suceda
        [t.join() for t in threads]

def pingme(num_threads,archivo):
    __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
    my_file = os.path.join(__location__, archivo)

    ping = Pingerson()
    if num_threads >= multiprocessing.cpu_count():
        ping.thread_count = multiprocessing.cpu_count()
    else:
        ping.thread_count = num_threads
    ping.hosts = importar_lista_ips2(my_file)

    return ping.start()

# Calling Ping

def func1():
    dic_viejo = (pingme(8, "arp.txt"))
    return (dic_viejo)

def func2():
    dic_nuevo = (pingme2(8, "arp.txt"))
    return (dic_nuevo)

print(func1())
print(func2())

输出

dic1: {'alive': ['192.168.0.1'], 'dead': ['192.168.0.10', '192.168.0.179']}
dic2: {'alive': ['192.168.0.1'],['192.168.0.1'] 'dead': ['192.168.0.10', '192.168.0.179'], ['192.168.0.10', '192.168.0.179']}

预期输出

dic1: {'alive': ['192.168.0.1'], 'dead': ['192.168.0.10', '192.168.0.179']}
dic2: {'alive': ['192.168.0.1'], 'dead': ['192.168.0.10', '192.168.0.179']}

0 个答案:

没有答案