# alg_cvsignal.py
#
# Some test code for cv_signal

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

# We need to increase resources for the wait code
import deadlock

# global state
testval = 0

# The lock variables
testlock = None
testcv   = None

# Test code
def thread_code( arg ):

    global testval

    lock_acquire( testlock )
    while( testval != 1 ):
        cv_wait( testcv, testlock )

    print "Thread woke!"

    # Signal the main thread
    testval = 2
    cv_signal( testcv, testlock )

    lock_release( testlock )

##
## Main code 
##
## test that cv_signal does something

def main( args ):

    # Modern versions of python require us to use the `global'
    # keyword to be able to write to global variables.
    global testval, testlock, testcv

    testlock = lock_create("testlock")
    testcv = cv_create("testcv")
    
    print "testing cv_signal"

    # Intruduce a race so that we don't know whether the thread
    # or this main code will sleep. Either way it will work, though
    testval = 0

    # Create the other thread
    name = "thread"
    thread_create( name, thread_code, None )

    testval = 1
    
    # Sleep until the other thread signals us
    lock_acquire( testlock )
    while( testval != 2 ):
        cv_wait( testcv, testlock )

    print "Main woke!"

    # Now we can exit 
    print "cv_signal test code exiting"
    exit(1)

