python的多线程示例

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
#!/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!


标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:用Python多线程抓取并验证代理

下一篇:Android 和java平台通用的AES加密解密