python的多线程示例
程序员文章站
2022-05-29 08:47:28
...
#!/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!
推荐阅读
-
常见的排序算法和查找算法——python实现
-
LeetCode 153. 寻找旋转排序数组中的最小值 Python
-
使用QTcpServer创建一个简单的服务器程序之二:多线程服务器(4)-服务端实现
-
python简单的http服务器
-
iOS多线程之理解RunLoop的CommonModes
-
python获取当前模块的名称 博客分类: python
-
使用Python创建简单的HTTP和FTP服务
-
socket做一个简单的web服务器处理多线程
-
ReentrantLockd的非公平锁lock方法实现源码解析 博客分类: java多线程 java
-
python-优矿-hurst指数与期货33品种的预测