加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python的多线程示例

发布时间:2020-12-17 17:29:09 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #!/usr/bin/env pythonimport subprocessfrom threading import Threadfrom Queue import Queuenum_threads = 3ips = ['127.0.0.1','10.103.13.156','

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#!/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站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读