前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python的多线程示例

python的多线程示例

原创
作者头像
好派笔记
修改2021-11-03 12:43:34
4140
修改2021-11-03 12:43:34
举报
文章被收录于专栏:好派笔记好派笔记
代码语言:javascript
复制
#!/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</pre> 


输出内容:
  
/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!  

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档