python的多线程示例

#!/usr/bin/env python
import subprocess
from threading import thread
from queue import queue
num_threads = 3
ips = [‘127.0.0.1’, ‘10.103.13.156’,’10.103.13.145′]
q = queue()
def pingme(i, queue):
while true:
ip = queue.get()
print ‘thread %s pinging %s ‘ % (i, ip)
ret = subprocess.call(‘ping -c 1 %s’ % ip, shell=true, stdout=open(‘/dev/null’), stderr=subprocess.stdout)
if ret == 0:
print ‘%s is alive!’ % ip
else:
print ‘%s is down…’ % ip
# start threads
for i in xrange(num_threads):
t = thread(target=pingme, args=(i, q))
t.setdaemon(true)
t.start()
for ip in ips:
q.put(ip)
print ‘main thread waiting…’
q.join()
print ‘done..’
if __name__ == ‘__main__’:
pass

输出内容:

/usr/bin/python2.7 /home/wuguowei/pycharmprojects/xplan_script/test_process/my_sub_process.py
thread 1 pinging 127.0.0.1
main thread waiting…thread 0 pinging 10.103.13.156
thread 2 pinging 10.103.13.145
127.0.0.1 is alive!
10.103.13.156 is alive!
10.103.13.145 is alive!

Posted in 未分类

发表评论