# alg_safe2.py
#
# Safe algorithm that acquires in order

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

# The semaphores
sem0 = None
sem1 = None

# A shared variable to count
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

    # Reduce output, but we still want some feedback on the screen
    if( counter % 127 == 0 ):
        print "Counter is %d in thread %d" % (counter, num)
        
# Code for the first thread
def thread_code( arg ):

    while( 1 ):
        # Acquire the semaphores
        # Because we always execute the same acquire code,
        # We always acquire in the same order
        P( sem0 )
        P( sem1 )
        
        # Do some work here 
        do_some_work( arg )
        
        # Release the semaphores
        V( sem0 )
        V( sem1 )

    
##
## Main code 
##

def main( args ):

    # Setup our semaphores
    # Need `global' to be able to write to them
    global sem0, sem1
    sem0 = sem_create( "sem0", 1 )
    sem1 = sem_create( "sem1", 1 )
    
    # Start a threads on the thread_code() function
    thread_create( "thread0", thread_code, 0 );
    thread_create( "thread1", thread_code, 1 );
