首页 > 后端开发 > Python教程 > python的多线程示例

python的多线程示例

大家讲道理
发布: 2016-11-09 10:58:05
原创
1233 人浏览过

#!/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!
登录后复制


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板