' thread_workqueue.pb — Work queue simulation
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL queueItems(100) AS LONG
    LOCAL queuePriorities(100) AS LONG
    LOCAL queueSize AS LONG
    LOCAL maxQueue AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL nextItem AS LONG
    LOCAL nextPriority AS LONG
    LOCAL bestIdx AS LONG
    LOCAL processedCount AS LONG
    LOCAL totalValue AS LONG
    LOCAL enqueueCount AS LONG
    LOCAL dequeueCount AS LONG
    LOCAL workerCount AS LONG
    LOCAL itemValue AS LONG
    LOCAL itemPriority AS LONG
    LOCAL workResult AS LONG
    LOCAL workSum AS LONG
    LOCAL iter AS LONG
    LOCAL tempPriority AS LONG
    LOCAL tempItem AS LONG

    maxQueue = 20
    queueSize = 0
    processedCount = 0

    PRINT "=== Work Queue Simulation ==="
    PRINT "Max queue: " + STR$(maxQueue)

    FOR enqueueCount = 1 TO 25
        IF queueSize < maxQueue THEN
            itemValue = enqueueCount * 10
            itemPriority = enqueueCount MOD 5
            queueItems(queueSize) = itemValue
            queuePriorities(queueSize) = itemPriority
            queueSize = queueSize + 1
            PRINT "  Enqueue: value=" + STR$(itemValue) + " prio=" + STR$(itemPriority)
        ELSE
            PRINT "  Queue full, dropping item"
        END IF
    NEXT enqueueCount

    PRINT "Queue size after enqueue: " + STR$(queueSize)

    FOR workerCount = 1 TO 15
        IF queueSize > 0 THEN
            bestIdx = 0
            nextPriority = queuePriorities(0)
            FOR i = 1 TO queueSize - 1
                IF queuePriorities(i) > nextPriority THEN
                    bestIdx = i
                    nextPriority = queuePriorities(i)
                END IF
            NEXT i

            nextItem = queueItems(bestIdx)
            nextPriority = queuePriorities(bestIdx)
            workResult = nextItem + nextPriority
            workSum = workSum + workResult
            processedCount = processedCount + 1

            FOR i = bestIdx TO queueSize - 2
                queueItems(i) = queueItems(i + 1)
                queuePriorities(i) = queuePriorities(i + 1)
            NEXT i
            queueSize = queueSize - 1

            PRINT "  Dequeue: value=" + STR$(nextItem) + " (prio " + STR$(nextPriority) + ")"
        ELSE
            PRINT "  Queue empty, worker idle"
        END IF
    NEXT workerCount

    PRINT "Processed: " + STR$(processedCount) + " Remaining: " + STR$(queueSize)
    PRINT "Work sum: " + STR$(workSum)
    PRINT "=== End Work Queue ==="
    FUNCTION = 0
END FUNCTION
