# alg_dead2.py
#
# Deadlock by two threads acquiring in a different order

# We want all the symbols from sim161
from sim161 import *

# The semaphore
sem0 = None
sem1 = None

# A shared variable
counter = 0

# Some work to do
# keep track of the global counter
# and print every now and again so we can visually see that we're running
def do_some_work( num ):
    global counter

    counter += 1

    print "Counter is %d in thread %d" % (counter, num)
        
# Code for the first thread
def thread0_code( arg ):

    while( 1 ):
        # Acquire the semaphores
        P( sem0 )
        P( sem1 )
        
        # Do some work here 
        do_some_work( 0 )
        
        # Release the semaphores
        V( sem0 )
        V( sem1 )

# Code for the second thread
def thread1_code( arg ):

    while( 1 ):
        # Acquire the semaphores -- DIFFERENT ORDER!
        P( sem1 )
        P( sem0 )
        
        # Do some work here 
        do_some_work( 1 )
        
        # Release the semaphores
        V( sem0 )
        V( sem1 )
    
##
## Main code 
##

def main( args ):

    # Setup our semaphores
    # We need 'global' to be able to write to the global variables
    global sem0, sem1
    sem0 = sem_create( "sem0", 1 )
    sem1 = sem_create( "sem1", 1 )
    
    # Start a threads on the thread_code() function
    thread_create( "thread0", thread0_code, None );
    thread_create( "thread1", thread1_code, None );
