' thread_atomic.pb — Atomic operation simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL counter AS LONG
    LOCAL sharedFlags(20) AS LONG
    LOCAL numFlags AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL oldVal AS LONG
    LOCAL newVal AS LONG
    LOCAL expected AS LONG
    LOCAL swapped AS LONG
    LOCAL incrementCount AS LONG
    LOCAL decrementCount AS LONG
    LOCAL compareCount AS LONG
    LOCAL exchangeCount AS LONG
    LOCAL iter AS LONG
    LOCAL totalOps AS LONG
    LOCAL tempVal AS LONG
    LOCAL flagVal AS LONG

    counter = 0
    numFlags = 10

    PRINT "=== Atomic Operations Simulation ==="

    FOR incrementCount = 1 TO 50
        oldVal = counter
        newVal = oldVal + 1
        counter = newVal
        totalOps = totalOps + 1
    NEXT incrementCount
    PRINT "Counter after 50 increments: " + STR$(counter)

    FOR decrementCount = 1 TO 20
        oldVal = counter
        newVal = oldVal - 1
        counter = newVal
        totalOps = totalOps + 1
    NEXT decrementCount
    PRINT "Counter after 20 decrements: " + STR$(counter)

    expected = 30
    newVal = 999
    IF counter = expected THEN
        counter = newVal
        swapped = 1
    ELSE
        swapped = 0
    END IF
    PRINT "CAS(" + STR$(expected) + " -> " + STR$(newVal) + ") : " + STR$(counter) + " swapped=" + STR$(swapped)
    totalOps = totalOps + 1

    counter = 0
    FOR compareCount = 1 TO 100
        oldVal = counter
        newVal = oldVal + 1
        counter = newVal
    NEXT compareCount
    PRINT "Counter after reset+100: " + STR$(counter)

    FOR i = 0 TO numFlags - 1
        sharedFlags(i) = 0
    NEXT i

    FOR exchangeCount = 1 TO 20
        i = exchangeCount MOD numFlags
        flagVal = sharedFlags(i)
        IF flagVal = 0 THEN
            sharedFlags(i) = 1
        ELSE
            sharedFlags(i) = 0
        END IF
        totalOps = totalOps + 1
    NEXT exchangeCount

    PRINT "Total atomic ops: " + STR$(totalOps)
    PRINT "Final counter: " + STR$(counter)
    PRINT "=== End Atomic ==="
    FUNCTION = 0
END FUNCTION
