import threading
import random
import time
class VehicleThread( threading.Thread ):
def __init__( self, threadName, event ):
threading.Thread.__init__( self, name = threadName )
self.threadEvent = event
def run( self ):
time.sleep( random.randrange( 1, 10 ) )
print "%s arrived at %s" % ( self.getName(), time.ctime( time.time() ) )
self.threadEvent.wait()
print "%s passes through intersection at %s" % ( self.getName(), time.ctime( time.time() ) )
greenLight = threading.Event()
vehicleThreads = []
for i in range( 1, 11 ):
vehicleThreads.append( VehicleThread( "Vehicle" + str( i ),greenLight ) )
for vehicle in vehicleThreads:
vehicle.start()
while threading.activeCount() > 1:
greenLight.clear()
print "RED LIGHT! at", time.ctime( time.time() )
time.sleep( 3 )
print "GREEN LIGHT! at", time.ctime( time.time() )
greenLight.set()
time.sleep( 1 )