CS352 threadedpingWithLocks.py

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

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


Exercise

  • Before trying the program below, modify the run() method so that its code is as follows:
   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] )
            #self.lock.acquire()
            #self.list.append( "%s: %s" % ( self.ip, self.report[ self.status ] ) )
            self.list.append( "%s: %s" % self.ip  )
            doSomethingTimeConsuming()
            self.list.append( "%s: %s" %  self.report[ self.status ]  )
            #self.lock.release()
  • Figure out why the output looks the way it does...
  • Then try the code below...

Solution

#! /usr/bin/python
# threadedpingWithLocks.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
# access to a list of string to which they must append their message.
import os
import re
import time
import sys
from threading import Thread, Lock
 
class testIpThread( Thread ):
   def __init__ ( self, ip, lock, list ):
      Thread.__init__(self)
      self.ip = ip
      self.status = -1
      self.lock = lock
      self.list = list
      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] )
            self.lock.acquire()
            self.list.append( "%s: %s" % ( self.ip, self.report[ self.status ] ) )
            #self.list.append( "%s: %s" % self.ip  )
            #doSomethingTimeConsuming()
            #self.list.append( "%s: %s" %  self.report[ self.status ]  )
            self.lock.release()

def doSomethingTimeConsumming():
    sum = 0
    for i in range( 100000 ):
        sum += i
        
def main():     
    pinglist = []
    lock = Lock()
    list = []
    for host in range(1,20):
       ip = "131.229.72."+str(host)
       current = testIpThread( ip,  lock, list )
       pinglist.append(current)
       current.start()
         
    for pingle in pinglist:
       pingle.join()

    for line in list:
        print line

    print "done!"

main()