线程中的全局变量更新和python中main的访问

时间:2015-03-18 13:22:29

标签: python multithreading python-2.7 global

我有特定的节目..

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任何ping都是不成功的,up所有ping都成功..函数node_check()正在执行因为打印正在进行中node_up数组..但程序似乎永远不会执行检查while(1)

的主node_up

任何人都可以指出我做错了吗。

2 个答案:

答案 0 :(得分:3)

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

thread.start_new_thread(node_check, ())

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

答案 1 :(得分: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