CS352 threadedpingWithSemaphores.py
--D. Thiebaut 01:30, 9 February 2010 (UTC)
#! /usr/bin/python
# threadedpingWithSemaphores.py
# D. Thiebaut
# from http://www.wellho.net/solutions/python-python-threads-a-first-example.html
# edited by D. Thiebaut
#
# Same version as the one with locks, but uses semaphores instead.
import os
import re
import time
import sys
from threading import Thread, Semaphore
class testIpThread( Thread ):
def __init__ ( self, ip, sem, list ):
Thread.__init__(self)
self.ip = ip
self.status = -1
self.sem = sem
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.sem.acquire()
#self.list.append( "%s: %s" % ( self.ip, self.report[ self.status ] ) )
self.list.append( "%s: " % self.ip )
doSomethingTimeConsumming()
self.list.append( " %s" % self.report[ self.status ] )
self.sem.release()
def doSomethingTimeConsumming():
sum = 0
for i in range( 100000 ):
sum += i
def main():
pinglist = []
sem = Semaphore()
list = []
for host in range(1,20):
ip = "131.229.72."+str(host)
current = testIpThread( ip, sem, list )
pinglist.append(current)
current.start()
for pingle in pinglist:
pingle.join()
for line in list:
print line
print "done!"
main()