' thread_rwlock.pb — Read-Write Lock simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL sharedData(100) AS LONG
    LOCAL readerCount AS LONG
    LOCAL writerActive AS LONG
    LOCAL numReaders AS LONG
    LOCAL numWriters AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL r AS LONG
    LOCAL w AS LONG
    LOCAL readSum AS LONG
    LOCAL writeVal AS LONG
    LOCAL conflictCount AS LONG
    LOCAL totalOps AS LONG
    LOCAL lockGranted AS LONG
    LOCAL iter AS LONG
    LOCAL operationCount AS LONG
    LOCAL dataSize AS LONG

    dataSize = 20
    FOR i = 0 TO dataSize - 1
        sharedData(i) = i * 10
    NEXT i

    readerCount = 0
    writerActive = 0
    conflictCount = 0

    PRINT "=== Read-Write Lock Simulation ==="
    PRINT "Data size: " + STR$(dataSize)

    FOR operationCount = 1 TO 30
        IF operationCount / 3 * 3 = operationCount THEN
            numWriters = 1
            numReaders = 0
        ELSE
            numWriters = 0
            numReaders = 2
        END IF

        IF writerActive = 0 AND readerCount = 0 THEN
            lockGranted = 1
        ELSE
            IF numWriters = 0 AND writerActive = 0 THEN
                lockGranted = 1
            ELSE
                lockGranted = 0
                conflictCount = conflictCount + 1
            END IF
        END IF

        IF lockGranted = 1 THEN
            IF numWriters > 0 THEN
                writerActive = 1
                writeVal = operationCount * 100
                FOR i = 0 TO dataSize - 1
                    sharedData(i) = writeVal + i
                NEXT i
                PRINT "  Write op " + STR$(operationCount) + ": data=" + STR$(writeVal)
                writerActive = 0
            END IF

            IF numReaders > 0 THEN
                readerCount = readerCount + numReaders
                readSum = 0
                FOR i = 0 TO dataSize - 1
                    readSum = readSum + sharedData(i)
                NEXT i
                PRINT "  Read op " + STR$(operationCount) + ": " + STR$(numReaders) + " readers, sum=" + STR$(readSum)
                readerCount = readerCount - numReaders
            END IF

            totalOps = totalOps + 1
        END IF
    NEXT operationCount

    PRINT "Successful ops: " + STR$(totalOps)
    PRINT "Conflicts: " + STR$(conflictCount)
    PRINT "=== End RWLock ==="
    FUNCTION = 0
END FUNCTION
