python中从线程更新全局变量和从main访问全局变量
我有特别的节目python中从线程更新全局变量和从main访问全局变量,python,multithreading,python-2.7,global,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(
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)
我希望这个程序打印notup
wen任何ping都不成功,并且up
wen所有ping都成功。。函数node\u check()
正在执行,因为node\u up
数组的打印正确。。但是程序似乎从不执行main,而(1)
检查节点是否向上
有人能指出我做错了什么吗?根据函数的定义,第一个参数应该是函数对象。但是您正在传递调用函数的结果。所以,像这样改变它
thread.start_new_thread(node_check, ())
现在将创建一个新线程,它将执行
节点检查
功能。这样做感觉很愚蠢。为什么不重构为使用queue.queue
s呢
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
谢谢你,伙计。。这么愚蠢的错误。。正在工作..将在8分钟后接受..:)