在 python 中从线程更新全局变量并从 main 访问

Global variable update from thread and access from main in python

我有特定的程序..

node_up = [0,0,0,0,0]
list_host = [ '10.0.2.12', '10.0.2.13', '10.0.2.14', '10.0.2.15', '10.0.2.16' ]

def node_check():
    global node_up, list_host
    for i in range( len(list_host) ):
        try:
            b = subprocess.check_output( ["ping", "-c", "4", "-w", "4", list_host[i] ] )
            print b
            node_up[i] = 1
            print node_up
        except subprocess.CalledProcessError, e:
            print e.output
            node_up[i] = 0
            print node_up


thread.start_new_thread( node_check(), () )
while(1):
    print "round"
    if 0 in node_up:
        print "not up"
        print node_up
    else:
        print "up"
        print node_up
    print "round"
    time.sleep(5)

我希望这个程序打印 not up wen 任何 ping 不成功,并且 up wen 所有 ping 成功..函数 node_check() 正在执行,因为打印正常使用 node_up 数组 .. 但程序似乎从未执行检查 node_up

的主要 while(1)

谁能指出我哪里做错了..

根据start_new_thread函数的定义,第一个参数应该是一个函数对象。但是你正在传递调用函数的结果。所以,改成这样

thread.start_new_thread(node_check, ())

现在将创建一个新线程,它将执行 node_check 函数。

感觉这样做很愚蠢。为什么不重构为使用 queue.Queues 呢?

import queue
import threading
import subprocess

QUEUE_TIMEOUT = 5
NUM_WORKER_THREADS = 5

HOST_LIST = ['10.0.2.12', '10.0.2.13', '10.0.2.14',
             '10.0.2.15', '10.0.2.16']

def node_check(host_q, response_q):
    try:
        host = host_q.get(timeout=QUEUE_TIMEOUT)
    except queue.Empty:
        return
    try:
        b = subprocess.check_output(["ping", "-c", "4", "-w", "4", host])
        response_q.put(True, timeout=QUEUE_TIMEOUT)
    except subprocess.CalledProcessError as e:
        response_q.put(False, timeout=QUEUE_TIMEOUT)
    host_q.task_done()

def main():
    host_queue = queue.Queue()
    response_queue = queue.Queue()

    for host in HOST_LIST:
        host_queue.put(host)


    threadlist = [threading.Thread(target=node_check,
                                   args=(host_queue, response_queue)) for
                  _ in range(NUM_WORKER_THREADS)]
    for t in threadlist:
        t.daemon = True
        t.start()
    host_queue.join() # wait for all hosts to be processed
    if all(host_queue.queue):
        # all nodes are up
    else:
        # some node is down