python 多執行緒之thread
#! /usr/bin/env python # -*- coding:utf-8 -*- from threading import Thread import subprocess from Queue import Queue num_threads = 3 ips = ['10.108.100.174', '119.75.218.77', '127.0.0.1'] q = Queue() def pingit(i, queue): while True: ip = queue.get() print "thread %s is pinging %s" % (i, ip) ret = subprocess.call('ping -c 3 %s' % ip, shell=True, stdout=open('/dev/null','w'))#正常則返回0,異常則返回1;stdout=open('/dev/null','w')遮蔽ping具體細節資訊 if ret != 0: print "%s is down" % ip queue.task_done() for i in xrange(num_threads):#xrang比range好 t = Thread(target=pingit, args=(i, q)) t.setDaemon(True)#設定了setDaemon則執行緒會隨著主執行緒關閉而關閉,python中,主執行緒結束後,會預設等待子執行緒結束後,主執行緒才退出 t.start() for ip in ips: q.put(ip) print "main thread is waiting..." q.join() print "Done..."