CS352 threadedpingWithQueues.py

From dftwiki3
Revision as of 21:33, 8 February 2010 by Thiebaut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 01:32, 9 February 2010 (UTC)


#! /usr/bin/python
# threadedpingWithQueues.py
# D. Thiebaut
# from http://www.wellho.net/solutions/python-python-threads-a-first-example.html
# edited by D. Thiebaut
#
# Same version as previous threaded one, except now the threads are given
# a queue in which they store their messages.  The queue is emptied by the
# main program
import os
import re
import time
import sys
from threading import Thread
from Queue import Queue
 
class testIpThread( Thread ):
   def __init__ ( self, ip, q ):
      Thread.__init__(self)
      self.ip = ip
      self.status = -1
      self.q = q
      self.lifeline = re.compile(r"(\d) received")
      self.report =  ( "No response", "Partial Response", "Alive")
      
   def run( self ):
      pingaling = os.popen( "ping -q -c2 " + self.ip, "r" )
      while True:
         line = pingaling.readline()
         if not line: break
         igot = re.findall( self.lifeline, line)
         if igot:
            self.status = int( igot[0] )
            message =  "%20s: %s" % ( self.ip, self.report[ self.status ] ) 
            self.q.put( message )
            
def doSomethingTimeConsumming():
    sum = 0
    for i in range( 100000 ):
        sum += i
        
def main():     
    pinglist = []
    q = Queue()
    for host in range(1,20):
       ip = "131.229.72."+str(host)
       current = testIpThread( ip, q )
       pinglist.append(current)
       current.start()
         
    for pingle in pinglist:
       pingle.join()

    while not q.empty():
       message = q.get()
       print message

    print "done!"

main()