python的多线程示例

前端之家收集整理的这篇文章主要介绍了python的多线程示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

#!/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!

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的Python相关文章