python多线程100进程一起ping演习笔记

  • 2019 年 11 月 28 日
  • 筆記

的subprocess模块进行播放语音方面,偶然遇到内存爆炸之类问题,so,想系统的学习一下python下的进程管理。本文代码在github上,文件夹是python_multithreading

使用多的原因是,每一个ping都需要有一段时间的返回,如果是单进程的话,可以先去喝杯咖啡了。使用一百个进程,则效率理论上可以提速一百倍(主要时间是消耗在网速,而不是cpu速度)。

基本实现思路是,首先用字符串处理,把需要遍历的本地网络192.168.0.0-192.168.2.255这部分全部变成列表的一个值,然后组建一个队列,按照设定的进程数,开始开辟进程,然后将队列的值开始一步步放进函数中,进行处理。根据返回值。判断是否ping是否联通。然后输出,

源码如下

Python

#!/usr/bin python from threading import Thread import subprocess from Queue import Queue num_threads = 100 #线程数 #采用字符串+运算,添加到列表中。 ips = ['192.168.0.1'] for i in range(2): for j in range(255): l = '192.168.'+str(i)+'.'+str(j) ips.append(l) #print(ips) q = Queue() #建立一个队列 #每个线程都调用同一个函数,i代表当前是第几个线程,导入队列 def pingme(i,queue): while True: ip = queue.get() #print('thread %s pinging %s' %(i,ip)) begin = datetime.datetime.now() ret = subprocess.call('ping -c 1 %s' % ip,shell=True,stdout=open('/dev/null','w'),stderr = subprocess.STDOUT) if ret == 0: print ('%s is alive!' %ip) elif ret == 1: pass #print ('%s is down…' %ip) queue.task_done() for i in range(num_threads): t=Thread(target=pingme,args=(i,q)) t.setDaemon(True) t.start() #print (i) for ip in ips: q.put(ip) #print (ip) print ('main thread waiting….') q.join() print ('done')

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

#!/usr/bin python from threading import Threadimport subprocessfrom Queue import Queue num_threads = 100#线程数#采用字符串+运算,添加到列表中。ips = ['192.168.0.1']for i in range(2):    for j in range(255):        l = '192.168.'+str(i)+'.'+str(j)        ips.append(l) #print(ips)q = Queue()#建立一个队列#每个线程都调用同一个函数,i代表当前是第几个线程,导入队列def pingme(i,queue):    while True:        ip = queue.get()        #print('thread %s pinging %s' %(i,ip))        begin = datetime.datetime.now()        ret = subprocess.call('ping -c 1 %s' % ip,shell=True,stdout=open('/dev/null','w'),stderr = subprocess.STDOUT)              if ret == 0:            print ('%s is alive!' %ip)        elif ret == 1:            pass            #print ('%s is down…' %ip)        queue.task_done() for i in range(num_threads):    t=Thread(target=pingme,args=(i,q))    t.setDaemon(True)    t.start()    #print (i)  for ip in ips:    q.put(ip)    #print (ip) print ('main thread waiting….')q.join()print ('done')

运行结果就是

main thread waiting…. 192.168.1.1 is alive! 192.168.1.100 is alive! 192.168.1.102 is alive! 192.168.1.104 is alive! 192.168.1.107 is alive! 192.168.1.106 is alive! done

原创文章,转载请注明: 转载自URl-team

本文链接地址: python多线程100进程一起ping演习笔记

  1. 操作系统-多进程和多线程-python
  2. python-opencv人脸识别与树莓派摄像头转头跟随()