' thread_barrier.pb — Barrier synchronization simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL threadStates(20) AS LONG
    LOCAL threadResults(20) AS LONG
    LOCAL numThreads AS LONG
    LOCAL numPhases AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL allArrived AS LONG
    LOCAL phaseCount AS LONG
    LOCAL arrivedCount AS LONG
    LOCAL totalWork AS LONG
    LOCAL workResult AS LONG
    LOCAL phaseResult AS LONG
    LOCAL iter AS LONG

    numThreads = 5
    numPhases = 4

    PRINT "=== Thread Barrier Simulation ==="
    PRINT "Threads: " + STR$(numThreads) + " Phases: " + STR$(numPhases)

    FOR phaseCount = 1 TO numPhases
        PRINT "--- Phase " + STR$(phaseCount) + " ---"

        FOR i = 0 TO numThreads - 1
            IF phaseCount = 1 THEN workResult = i * 10
            IF phaseCount = 2 THEN workResult = i * 20
            IF phaseCount = 3 THEN workResult = i * 30
            IF phaseCount = 4 THEN workResult = i * 40
            threadResults(i) = workResult
            threadStates(i) = 1
            totalWork = totalWork + workResult
        NEXT i

        arrivedCount = 0
        FOR i = 0 TO numThreads - 1
            IF threadStates(i) = 1 THEN
                arrivedCount = arrivedCount + 1
            END IF
        NEXT i

        IF arrivedCount = numThreads THEN
            allArrived = 1
        ELSE
            allArrived = 0
        END IF

        IF allArrived = 1 THEN
            phaseResult = 0
            FOR i = 0 TO numThreads - 1
                phaseResult = phaseResult + threadResults(i)
            NEXT i
            PRINT "  Barrier: all " + STR$(arrivedCount) + " threads arrived"
            PRINT "  Phase sum: " + STR$(phaseResult)
        ELSE
            PRINT "  Barrier: " + STR$(arrivedCount) + " of " + STR$(numThreads) + " arrived"
        END IF

        FOR i = 0 TO numThreads - 1
            threadStates(i) = 0
        NEXT i
    NEXT phaseCount

    PRINT "Total work: " + STR$(totalWork)
    PRINT "=== End Barrier ==="
    FUNCTION = 0
END FUNCTION
