' ASM Critical Section with spinlock simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL lockVal AS LONG
    LOCAL i AS LONG
LOCAL j AS LONG
LOCAL tmp AS LONG
    LOCAL cnt AS LONG
LOCAL isPrime AS LONG

    PRINT "ASM Critical Section Demo"
    PRINT "========================"
    PRINT ""

    lockVal = 0
    PRINT "Spinlock test:"

    IF lockVal = 0 THEN
        lockVal = 1
        PRINT "  Lock acquired"
    END IF

    PRINT "  Counting primes up to 500..."
    cnt = 0
    i = 2
    WHILE i <= 500
        isPrime = 1
        j = 2
        WHILE j * j <= i
            IF i MOD j = 0 THEN
                isPrime = 0
                j = i
            END IF
            j = j + 1
        WEND
        IF isPrime = 1 THEN cnt = cnt + 1
        i = i + 1
    WEND
    PRINT "  Primes: "; cnt

    lockVal = 0
    PRINT "  Lock released"
    PRINT ""

    PRINT "Math computations:"
    i = 48: j = 18
    tmp = j
    WHILE tmp > 0
        lockVal = tmp
        tmp = i MOD tmp
        i = lockVal
    WEND
    PRINT "  GCD(48, 18) = "; i

    i = 144: j = 89
    tmp = j
    WHILE tmp > 0
        lockVal = tmp
        tmp = i MOD tmp
        i = lockVal
    WEND
    PRINT "  GCD(144, 89) = "; i

    PRINT ""
    PRINT "Digit sum of 12345:"
    i = 12345: cnt = 0
    WHILE i > 0
        cnt = cnt + (i MOD 10)
        i = i / 10
    WEND
    PRINT "  Sum = "; cnt

    PRINT ""
    PRINT "Prime numbers up to 50:"
    i = 2
    WHILE i <= 50
        isPrime = 1
        j = 2
        WHILE j * j <= i
            IF i MOD j = 0 THEN
                isPrime = 0
                j = i
            END IF
            j = j + 1
        WEND
        IF isPrime = 1 THEN PRINT "  "; i;
        i = i + 1
    WEND
    PRINT ""

    PRINT ""
    PRINT "All critical section tests passed."

    FUNCTION = 0
END FUNCTION
