Python中线程更新全局变量并从主线程访问

3
我有一个特定的程序...
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)

我希望这个程序在任何ping不成功时都能打印出“not up”,当所有ping成功时,则打印“up”。函数node_check()正在执行,因为通过node_up数组来输出正常。但是程序似乎从未执行检查node_up的主要while(1)。有人能指出我做错了什么吗?
2个回答

3
根据start_new_thread函数的定义,第一个参数应该是一个函数对象。但是你传递了调用函数后的结果。所以请将其更改为以下内容。
thread.start_new_thread(node_check, ())

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

1
谢谢,老兄。是我犯了个愚蠢的错误。现在它可以工作了。8分钟后我会接受的 :) - Haris

1
这种做法看起来有些愚蠢。为什么不重构代码,使用 queue.Queue 代替呢?
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接