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人臉識別與樹莓派攝影機轉頭跟隨()