7. Concurrency


7. Concurrency

This chapter covers how the RVM runs ooRexx's concurrent constructs: activities and the scheduler, object locks (guarded methods, GUARD, REPLY), START and Message objects, EventSemaphore / MutexSemaphore, the timer clock, Alarm / Ticker, Message~halt, and UNINIT at program end. It assumes the machine loop, activations and frames of the machine and the object model of objects. Both hosts implement the same model; differences are noted where they exist.

The activity model

An activity is the RVM's equivalent of an ooRexx thread (Activity.cpp). The RVM has no host threads: activities are green threads multiplexed on one machine loop. Exactly one activity runs at any time.

Concept ooRexx host JS host
Activity record RVM.Activity (../RVM.Objects.cls) Activity (../js/objects.mjs)
Scheduler RVM.Scheduler Scheduler
Run loop RVM.Machine~run (../RVM.Machine.cls) Machine.run (../js/machine.mjs)
Machine state of a waiting activity its registers, saved as .context~variables in act~regs its own Machine object (act.machine) plus a resume callback

An activity has its own RVM.Context (activation stack, NUMERIC, TRACE, traps, condition, clock). What all activities share is handed over through the context's globals (globals / shareGlobals: output, external data queue, command host, the program's stream table, clause texts) and the world (adoptWorld: classes, .local, .environment, the scheduler).

Activity states: NEW, READY, RUNNING, WAITING, ENDED. Other fields record what it waits for (waitingOn: an RVM.Pool, an RVM.MessageState, a semaphore or an I/O wait), a lock granted while waiting (granted), GUARD WHEN state (guarding, relock, watches), the START message it runs (message), the error that ended it (error), a semaphore result (waitResult), a timer (timer), the mutexes it holds (mutexes), and the UNINIT list of the final activity (uninits).

Activities are created by:

  • the run itself: the main activity (isMain), whose context is the program's;
  • REPLY: the method's current activation moves to a new activity (REPLY);
  • START / STARTWITH (Object and Message) and Message~reply: a new activity whose first activation only sends the message (START);
  • the end of the run, when objects are due UNINIT (UNINIT).

RexxContext~thread and a TraceObject's THREAD give the running activity's id (scheduler~nextId: 1 for main, then one per REPLY/START), see reflection.

How a wait works

ooRexx host. execute is the machine. When an activity must wait, the machine jumps to Suspend: it stores resumeAt (a label), sets the state to WAITING, saves every local variable of execute (.context~variables) into act~regs, and returns "WAITING". When the activity is scheduled again, execute restores the registers with VALUE and does Signal Value act~resumeAt. Resume points:

resumeAt Meaning
RESUME continue at pc (slice expiry)
GRANTED an object lock was granted while waiting
GUARDRESUME a GUARD WHEN variable changed: re-lock, re-evaluate
SENDLOOP a native that returned RVM.Wait is sent again
DOSEND first run of a START activity: send its message
REPLYSTART first run of a REPLY activity that re-traces >I>
CMDRESUMED a command it waited for has ended: finish it
STDINRESUMED what a read of standard input needs has been read: the instruction again (or a HALT cut it short)
STDINSENT the same for a Stream method: it is sent again

DoReply and SpawnStart build the new activity's registers by copying the current ones and overriding stack, frames, pauses, flow state and the slice (and, for a REPLY in a nested machine, its nesting: REPLY).

JS host. Each activity has its own Machine; spawn clones the running machine's registers into a new one. suspend(resume, ready) stores a callback in this.resume, sets WAITING and throws the WAITING symbol; execute catches it and returns "WAITING". On the next run, executeBody calls the callback first (e.g. guardResume, re-sending the message), then re-enters the loop.

Natives that wait. A native method never blocks. It returns a marker to the machine: RVM.Wait(on) (wait for a lock, a message's completion or a semaphore, then send the same message again), RVM.StartMessage (spawn a START activity), or RVM.Reraise (raise a message's error again). On the re-send, a semaphore native finds act~waitResult set and returns it (semDone sets it). The WaitFor label (JS: the equivalent in doSend) registers the activity with what it waits for.

Nested machines wait in place. A machine run by a native for an immediate result — runSync, sendSync, a thunk (ADDRESS WITH target, environment symbol thunks; see synchronous execution) — runs in its caller's activity, whose frames are below it on the host stack. A wait there (a lock held by another activity, GUARD WHEN, Message~result of an incomplete message, a semaphore, SysSleep) cannot return to the run loop: instead the machine runs the scheduler in place (pump), launching the other activities until its own is ready, and then goes on where it stopped. While it waits, its activity is trapped (sched~trapped, a stack): the scheduler does not give a trapped activity, even when it is ready, because only the pump that trapped it can go back to it. This is a stack discipline: if an activity run by the pump waits in a nested machine of its own, the one below cannot go on until that one has. When nothing can run, the pump raises 93.900 in the waiting code: "RVM: nested waits cross (an activity waits below this one)" when what it waits for needs a trapped activity to go on first, and "RVM: an activity waits for something that cannot come" when nothing can end the wait (native would block for ever; at the top level the run would end). A REPLY there gives the native its value, and the rest of the method runs in a new activity that is not nested (REPLY).

t = .table~new
t[.key~new] = 'v'         -- HASHCODE runs in a nested machine (sendSync)
::class key
::method hashcode
  call SysSleep 0.1       -- waits in place: the other activities run
  return 'abcd'

The scheduler

RVM.Machine~run creates the scheduler, makes the main activity and loops:

loop
  outcome = launch(act)            -- WAITING, ENDED or FAILED
  if outcome \== WAITING then EndActivity(act)
  act = sched~next                 -- first ready activity, or .nil
  if act == .nil then act = uninitActivity()   -- objects due UNINIT
  if act == .nil then leave
end
  • Ready queue: FIFO by readiness (ready appends; a READY or ENDED activity is not queued twice). live lists activities not yet ended.
  • Switching happens only when the running activity waits, ends, or its slice expires. A switch never happens inside an instruction.
  • Time slicing is by clause count, not by time. At every CLAUSE instruction the machine decrements sliceLeft; when it reaches 0 it is reset to sched~slice and, if sched~othersReady (another activity is ready, after polling I/O and, with the real clock, firing due timers), the activity is re-queued at the end (yielding, resumeAt = RESUME) and the next one runs. The default slice is 10,000 clauses; RVM_SLICE=n changes it and RVM_SLICE=0 disables slicing (an activity runs until it waits or ends). Nested machines never yield.
  • End of the run. When no activity is ready and no timer or I/O wait can make one ready, the run ends — even if activities are still waiting (they wait for something that can no longer come; native ooRexx would hang). The exit code is the main program's.
e = .EventSemaphore~new
say 'waiting for nothing'
e~wait                 -- nobody can post it: the RVM ends here, rc 0
say 'unreachable'      -- (native ooRexx hangs)

Activity end and errors

launch runs an activity and returns WAITING, ENDED or FAILED. EndActivity handles the outcome:

  • An error that ends a non-main activity is reported when it happens (ErrorReport on the error stream) and does not change the exit code; other activities go on.
  • If the activity ran a START message, the message records the error (failed, info) and its waiters wake; Message~result then re-raises it (RVM.Reraise; as reraiseException: same condition object, traceback lines kept, position of the RESULT).
  • The main activity's error becomes the run's exit code. It is raised up to the runner (which reports it) only when no other activity is alive and no UNINITs are pending; otherwise it is reported at once and the run continues.
  • RVM.Scheduler~ended marks the activity ENDED, drops its GUARD WHEN watches, cancels its timer and any I/O wait, and force-releases the MutexSemaphores it holds (forceRelease, as forceLockRelease). RVM.Context~endActivity releases the object lock of its first activation.

RVM_ACTTRACE (any non-empty value) prints ACT id outcome resumeAt (JS: ACT id outcome) on the error stream after each launch — a debugging aid.

Object locks

Each object has one variable pool per scope (RVM.Pool, JS Pool, a subclass of the cell dictionary RVM.Vars). A pool carries a lock with the semantics of ooRexx's VariableDictionary (reserve, release, transfer):

  • owner, count (re-entrant: the owning activity may take it again), waiting (FIFO). release decrements; at 0 the lock goes to the first waiter, which is marked granted and woken.
  • reserve by a different activity first runs owner~checkDeadLock(act): it follows waitingOn~owningActivity links (pool owner, or a START message's activity) and raises 98.905 in the requesting activity if the chain returns to it. Semaphores report no owning activity, so they never take part in deadlock detection (as native).

Who takes the lock:

Code Lock
Rexx method, default (GUARDED) taken at entry (EnterMethod), before the first clause; held until the activation ends (popActivation → RVM.Level~unlock)
UNGUARDED method not taken
::ATTRIBUTE getter/setter, DELEGATE guarded by default: taken just for the read/write (RVM.Wait if busy, re-sent with granted)
::CONSTANT, compiled (native) methods never

If a guarded method must wait at entry, the machine first sets the current clause to the method's first clause so that a 98.905 is reported there (EXPOSE included), as native.

RVM.Level (the activation record) holds pool, locked and replied.

GUARD

  • GUARD ON takes the lock if the activation does not hold it (may wait: GRANTED); GUARD OFF releases it (lv~unlock). Outside a method activation (including an internal routine called from one): 99.911.
  • GUARD ON|OFF WHEN expr compiles to GUARD followed by the expression and GWHEN top k (R-code). The value must be 0 or 1 (34.902). If 0, the activity watches the variables k, remembers whether it held the lock (relock), releases it once, and suspends (GUARDRESUME). When a watched variable is assigned or dropped (even to the same value) the activity is woken (guardPost); it re-takes the lock if it had it and re-evaluates the expression from top.
  • Watched names (GuardNames in ../RVM.Compiler.cls, ooRexx's captureGuardVariable): simple variables and stems read by the expression that the method exposes (EXPOSE names, or, after USE LOCAL, the non-local names). For a compound, its stem and its tail variables are watched, not the element: changing b.1 does not wake guard on when b.1='x' (native hangs; the RVM ends the run if nothing else is ready). No watchable variable is 99.913, raised by the parser at translation (the compiler still emits an ERR 99.913 as a guard that should not be reached).
  • Notification: a watched cell calls pool~changed(name). ooRexx host: RVM.Var~watchBy; JS: the watched cell gets an accessor (Object.defineProperty). Also attribute setters notify.
  • Because GUARD WHEN releases the lock only once, a method that holds it twice (nested guarded calls in the same activity) keeps other activities blocked while it waits — as native.

REPLY

REPLY [expr] (REPLY / REPLYV), method activations only (99.919; translation-time in practice), at most once (98.935). DoReply (JS reply):

  1. If the entry was traced, <I< is traced now in the caller's activity.
  2. context~replyContext builds a new context that takes the current activation (activationState / takeActivation: variables, NUMERIC, traps, trace state, clock, security manager, stream scope) and its RVM.Level; the old context gets a substitute level.
  3. A new activity is created with the method's registers (fresh stack and frames). With >I> tracing, it re-traces the entry when it first runs (REPLYSTART) and the exit again at its end. Its machine is a top-level one even when the REPLY runs in a nested machine (code a native runs: runSync, sendSync, a thunk): not nested, not synchronous, its frames from 0; and the native gets the value now, as native's.
  4. The lock goes along: pool~transfer(newAct) passes it if held once; if held more than once (another activation of the same activity holds it too) it is released once and the new activity queues for it immediately (native: the new thread requests it on start, which nearly always happens before the caller releases).
  5. The caller continues as if the method had returned the value (DoReturn).

After REPLY, RETURN expr is 98.936 and EXIT expr is 98.937. USE STRICT ARG and FORWARD check the level type (METHOD), not the machine frame, because a REPLY activity's method has no frame.

START

Object~start(name, args...), Object~startWith, Message~start, Message~startWith and Message~reply / replyWith (which start a copy, copyMessage, carrying the notification parties) return RVM.StartMessage; the machine (SpawnStart, JS spawnStart) creates a context with activityContext (shared globals, invocation METHOD), a new activity with message set, and resume point DOSEND with send mode START. Its first activation only sends the message and is hidden from tracebacks (stackLines, ErrorLines). When the method returns, Deliver (mode START) stores the result, wakes waiters, notifies parties, and the activity finishes.

o = .worker~new
say 'got' o~work            -- got 42
m = o~start('slow', 3)
say m~completed             -- 0
say m~result                -- waits; 6
::class worker
::method work
  reply 42
  say 'after reply'         -- runs in a new activity
::method slow
  use arg n
  return n*2

Message objects

A Message's native value is RVM.MessageState (ooRexx's MessageClass): receiver, name, scope, arguments, result, returned, failed, info (condition), activated (START was used), startActivity, waiting, parties, notified. Natives: MessageNative, NewMessage, StartMessage, CheckReuse (../RVM.Objects.cls; JS equivalents in ../js/objects.mjs).

Method Behaviour
NEW(target, name [, 'I', args... \| 'A', array]) 93.901 if fewer than 2 args; option not A/I 93.915; with A exactly 4 args (93.901/93.902)
SEND, SENDWITH a delegate to the receiver; RVM.MessageSent stores the result, wakes waiters, notifies, returns the result
START, STARTWITH, REPLY, REPLYWITH see START; a started message cannot be sent/started/replied again (98.915)
RESULT waits until complete (RVM.Wait); re-raises its error (RVM.Reraise); .nil without a result
WAIT waits until complete
COMPLETED, HASERROR, HASRESULT, ERRORCONDITION, TARGET, MESSAGENAME, ARGUMENTS inspection
NOTIFY(t) t must be a MessageNotification (88.914); see below
HALT([desc]) see HALT

A wait on a message running in another activity first checks for a circular wait (startActivity~checkDeadLock): if that activity waits, directly or through a chain of lock owners, for the requesting one, the request raises 98.905.

NOTIFY. Parties are recorded in order. When the message completes, each gets MESSAGECOMPLETE(msg) (notifyAll → RVM.Notifier, a chain of delegates), then notified is set; a party added after that is notified immediately. Where it happens: for SEND, before SEND returns its result; for START, in the START activity when the result arrives; for a START that fails, before the activity ends and its error is reported. Message itself inherits MessageNotification and AlarmNotification (set up at bootstrap), so its own MESSAGECOMPLETE / TRIGGERED send it without a result — this is how messages are chained.

Failing SEND. As native (setObjNotify / notifyObject), SEND marks the sending activation (RVM.Level~notifyMsg; cleared by RVM.MessageSent~next). If a SYNTAX error unwinds through that activation (FailedUnwind in the ooRexx host; failed + unwind in JS), the message gets the error, its waiters wake and its parties are notified during the unwind, before the error is trapped or reported. The ooRexx host saves the unwind state (mode UNWIND) while MESSAGECOMPLETE methods run and restores it in Deliver; since a notification may have trapped an error of its own (the host's current condition then), the error that goes on out of the machine is raised again from the saved one (PropagateCo), not propagated.

Semaphores

EventSemaphore and MutexSemaphore are classes of the object core (not prelude Rexx code), implemented by SemaphoreNative with native values RVM.EventSem (ooRexx's SysSemaphore) and RVM.MutexSem (SysMutex, a recursive pthread mutex, plus MutexSemaphoreClass's nest count). NEW sends INIT.

Class Methods
EventSemaphore POST (wakes all waiters, whose WAIT returns 1), RESET, WAIT([t]) → 1 posted / 0 timeout, ISPOSTED, UNINIT (Unix: nothing visible, a closed event semaphore keeps working, as native; Windows: its handle is closed, and then POST and RESET do nothing, ISPOSTED and any timed WAIT are 0, a WAIT for ever is 1 at once)
MutexSemaphore ACQUIRE([t]) → 1 / 0, RELEASE → 1 / 0, UNINIT (Windows: its handle is closed, and then ACQUIRE(0) is 1 (its WaitForSingleObject fails, which is not a timeout), any other ACQUIRE and every RELEASE 0)

Timeout argument (TimeoutArg): omitted or -1 is forever; a TimeSpan (or an instance of a subclass) is sent TOTALSECONDS now (sendSync, as native's sendMessage: an override counts, an error in it goes up to the caller of WAIT/ACQUIRE, and no result is 88.901); any other value, or what TOTALSECONDS gave, is taken by its string value (a MutableBuffer, a stem, an object with a STRING method) as a number of seconds (88.902 "The timeout argument must be a number"); negative or greater than 4,294,967 s is forever; 0 means "do not wait".

Mutex details, reproducing native quirks: owner, depth (pthread recursion), nest (the object's acquire count), closed, destroyed. A full release grants the mutex to the first waiter. RELEASE returns 0 when the object counts no acquires, when the caller is not the owner (EPERM), or after destruction (EINVAL). UNINIT closes: ACQUIRE with no timeout or a non-zero timeout then returns 0; it destroys the mutex only if nobody holds it (else EBUSY: ACQUIRE(0) and RELEASE, which go straight to pthread, keep working). An activity that ends releases all mutexes it holds.

A semaphore wait returns RVM.Wait(sem), adding an RVM.Timer when the timeout is finite; semDone(r) cancels the timer, stores waitResult and wakes the activity; the re-sent message returns r.

SysSleep(secs) (../RVM.RexxUtil.cls, ../js/rexxutil.mjs) is a timed wait on a fresh RVM.EventSem that nobody posts, so other activities run while it sleeps; 0 seconds does not wait (no yield). RexxQueue~linein on an empty existing queue (REXX_LINEIN_QUEUE) also waits on an event semaphore that QUEUE / PUSH post (see I/O).

REXXUTIL's named semaphores (SysCreateEventSem, SysCreateMutexSem...) are not provided: ooRexx deprecates them in favour of the EventSemaphore and MutexSemaphore classes (17).

The clock

The scheduler's clock is used only by timed waits: EventSemaphore~wait(t), MutexSemaphore~acquire(t), SysSleep, the Alarm/Ticker timers and socket timeouts. It never drives scheduling of running activities. Timers (addTimer, cancelTimer, fireTimers) are kept sorted by deadline; equal deadlines fire in creation order; a firing timer calls on~timeout(act), which removes the activity from the semaphore's waiters and gives it 0.

Mode Behaviour
real (default; RVM_CLOCK=real or unset) milliseconds since first use (ooRexx host TIME('F'), JS Date.now()). Due timers fire at scheduling points: when an activity waits or ends (next) and at slice expiry (othersReady). If nothing is ready, the scheduler really sleeps until the first deadline (ooRexx host: the host's SysSleep; JS: Atomics.wait, or a busy wait where blocking is not allowed, e.g. a browser main thread).
virtual (RVM_CLOCK=virtual) starts at 0 and advances only when no activity is ready, jumping straight to the first deadline. Runs are deterministic and take no wall time.

With the virtual clock, TIME and DATE add the skipped time (RVM.Scheduler~skipped, used by the TIME/DATE BIFs), so call SysSleep 1 advances TIME('E') by one second. Time spent in a busy loop does not advance the virtual clock, so a program that busy-waits for a timer never sees it fire:

m = .o~new~start('spin')     -- spin: do forever; nop; end
call SysSleep 0.1            -- virtual clock: never wakes up, 'spin' is always ready

Pending socket I/O (addIO, pollIO; see libraries) is always waited for in real time, even under the virtual clock, because the other end is outside the RVM; the run does not end while I/O is pending.

Alarm and Ticker

Alarm, Ticker, AlarmNotification and MessageNotification are the Rexx classes from ooRexx's CoreClasses, in the prelude (../prelude.orx). Their native parts are ::METHOD ... EXTERNAL 'LIBRARY REXX f' methods (native TimeSupport.cpp): the compiler gives such methods the type REXX f (loader key X.f) and LibraryNative implements them:

f Implementation
ALARM_STARTTIMER(days, ms) creates an EventSemaphore, stores it in EVENTSEMHANDLE, sets TIMERSTARTED (via SetObjectVariable, which wakes GUARD WHEN timerStarted), waits on it for days*86400000+ms
TICKER_CREATETIMER creates the semaphore into EVENTSEMHANDLE
TICKER_WAITTIMER(handle, days, ms) timed wait on the handle
ALARM_STOPTIMER(h), TICKER_STOPTIMER(h) post the handle (ends the wait early)

The Rexx logic is native's: Alarm~init validates, does GUARD OFF; REPLY, waits in the new activity, and sends TRIGGERED unless cancelled; CANCEL waits for timerStarted then stops the timer. Ticker loops until cancelled. An unknown f is 90.998.

HALT

Message~halt([desc]) (as MessageClass::halt / RexxActivation::halt): returns 0 if the message was not started or a HALT is already pending, 1 if the activity has ended, otherwise sets haltPending / haltDesc on the activation currently running in the message's activity (RVM.Context~halt) and flags a clause boundary. desc must have a string value (88.909 for an object without one, as native).

Processing (RunTraps): at the next clause boundary of that activation, after pending CALL ON traps, a HALT condition is raised with the description; untrapped it is error 4.1 (the description is lost, as native). A SIGNAL ON HALT trap goes at that boundary; a CALL ON HALT trap is queued, as native's (processClauseBoundary raises it, and the queued trap runs at the next boundary): the machine holds it one clause (heldHalt, queued again by the next CLAUSE after its check), so the handler runs after one more clause, with SIGL that clause's line (after a CALL, the routine has run; before a DO, its first iteration has not). A CALL ON trap that returns re-flags the boundary (popActivation) so a pending HALT is still seen; an activation that ends before its next clause loses the HALT (as native); a waiting activity processes it when it wakes, at its next clause. A HALT does not interrupt a semaphore wait. Because a SEND records the sender's activity as startActivity, halting a SENDed message halts the sender. ADDRESS HostEmu's HI uses the same mechanism (I/O).

Ctrl-C

Native ooRexx turns SIGINT, SIGTERM and SIGHUP into a HALT, without a description, for every activity that is running or waiting (signalHandler → Interpreter::haltAllActivities → Activity::halt: its top Rexx frame). The RVM does the same: RVM.Scheduler~haltAll / Scheduler.haltAll marks the HALT pending (RVM.Context~halt) in every activity that has started and not ended, in the context of the code it runs now (topContext: that of its innermost runSync / sendSync, which the activity keeps in syncs; else its own), and the HALT is processed as above. An activity in SysSleep wakes at once (its EventSem is marked sleep: the timer is cancelled and the wait gives 0), as native's sleep is cut short by the signal. An activity that waits for standard input (see Blocking operations) wakes too (RVM.StdinWait's halted), and the instruction that read gets the HALT then, as for a HALT in a helper of the ooRexx host (below): native's read is cut short (the reader goes on, and what it reads is kept for the next read). Other waits (a semaphore, a message, a command) go on, as native's.

How the signal reaches the machine differs:

  • ooRexx host. The host interpreter takes the signal and raises HALT in its own top Rexx frame. execute, run, pump and the scheduler's next (where it sleeps) trap it (Call On Halt Name HostHalt): the handler calls haltAll and returns, and the machine goes on. When the frame is a helper of the machine (RVM.Number, a native...), the HALT is untrapped there: a SYNTAX 4.1 that reaches execute's Failed, which tells it from the machine's own 4.1 (description RVM.Halt). The instruction that called the helper is abandoned (pc, sp back to its start), haltAll is called, and RunTraps runs with again at that instruction: a SIGNAL ON HALT leaves it, an untrapped HALT is error 4.1, and a CALL ON HALT handler that returns runs the instruction again, from its start. (A HALT that falls in a helper that returns before its next clause is lost; a second Ctrl-C works.) The pollers of the I/O waits (commands, standard input) trap it as next does, and end their poll; the host's threads of commands and readers trap theirs (a command's thread ends when its command does).
  • JS host. Node runs a signal handler only when its event loop is free, and the machine never frees it; so rvm.mjs runs the program in a worker (14). The main thread takes the signal and sets a shared flag (interrupt.mjs); the machine looks at it at every CLAUSE and LABEL (one Atomics.load), and the scheduler after it sleeps (the sleep waits on the flag, and the signal wakes it). A second signal before the first is taken ends the process with the signal's status (128 + signal number): the machine is blocked (a read of standard input that could not wait, a command waited for) and cannot take it. The scheduler takes the flag when an I/O wait it polled for ends early because of it.

Tests: tests/signal/ (16).

UNINIT

UNINIT runs only at program end, never on DROP or mid-run garbage collection.

  • RVM.World~created records, in creation order, every object that has a non-private UNINIT method (instances, hand-made NEWs, classes with a class UNINIT, objects given one by SETMETHOD).
  • When no activity is ready, uninitsDue (ooRexx's lastChanceUninit) marks everything reachable from .environment (MarkValue: object → class, pools, native value; class → superclasses, metaclass, not subclasses; stem → values; message → receiver, args, result, parties; host collections → items and indexes). .local is not a root. Unmarked recorded objects are due.
  • They get UNINIT one after another, in creation order, in a fresh activity (uninitActivity, UninitNext; JS uninitNext, a loop rather than a recursion). Errors in UNINIT are discarded and the next one runs; the exit code is unchanged. Objects created during UNINITs are handled in a further round.
  • After a program-ending error, the report comes first, then UNINITs.
a = .u~new('a'); .local~k = .u~new('local'); .environment~k = .u~new('env')
-- at end: "uninit a", "uninit local"; 'env' is reachable and gets none

Blocking operations

Besides the waits described above, three kinds of host operations suspend only their activity, as I/O waits of the scheduler (addIO; each wait has its poller, and pollIO polls them: one kind waits in its poller, several in turn in steps of 10 ms):

  • Commands (ADDRESS, IssueCommand). When something else may run meanwhile (another activity that has not ended, or a timer: Scheduler~othersThan), outside a nested machine and an interactive pause, a command that the host runs is started without waiting (RVM.CommandHost~start) and the CMD instruction makes its activity wait (RVM.CommandWait, polled by RVM.CommandPoller). When the command ends, the activity finishes it where it stopped (CmdResumed: its output and error to their targets, RC, .RS, its trace and condition), as native, whose command blocks only its own thread. A server and its clients started as commands from START activities work (the ooTest socket samples). Otherwise (the common case) the command runs as before, waited for. The ooRexx host runs it in a thread of its own (RVM.CommandJob, a method that REPLYs: ooRexx gives up its lock while a command runs), which posts an EventSemaphore when it ends; Node starts a small Node process (spawn) that runs it and writes its status to a file, which the poller looks for (flushing standard output first, so that what the program wrote comes out before what the command writes, as natively).

  • Reads of standard input when it is a terminal or a pipe: LINEIN, CHARIN, PULL and PARSE PULL (an empty queue), PARSE LINEIN, and the LINEIN, CHARIN and ARRAYIN methods of a Stream on standard input (.INPUT and .STDIN among them). When something else may run (othersThan; in Node also when standard input is a terminal, so that Ctrl-C cuts the read short), outside a nested machine and an interactive pause, the machine lets the read wait (StdinGate: the gate, RVM.StdinReader~gate or JS STDIN_GATE, is the reading context). The stream operation, before it does anything (RVM.Stream~inputNeed), sees whether what it needs (a line, n bytes, everything) has been read; if not, it gives an RVM.StdinNeed, and its activity waits (RVM.StdinWait, polled by RVM.StdinPoller) while a reader reads a chunk of standard input. Then the instruction (or the Stream method, which is sent again) runs again from its start, nothing it did before showing, and takes what it needs from what was read. The reader is a process, dd bs=N count=1, that inherits standard input: one read of the system, at most 4096 bytes in the ooRexx host (as SysFile), 64 KiB in Node. The ooRexx host runs it from a thread of its own (RVM.StdinJob, as a command), Node from its main thread (rvm.mjs, which hands the bytes over in a SharedArrayBuffer: 14). Several activities that wait are served in the order they asked. Every read of standard input, waiting or not, takes first what was read ahead for one that waited (RVM.StdinReader, NodeHost's stdinBuffer), and one that cannot wait while a reader reads waits for it. The ooRexx host lets a read take what the system says is already there (FIONREAD, the CHARS of its .Input) without a reader; Node, which cannot ask, needs one for each chunk (and its LINES and CHARS of a pipe start one and wait 10 ms at most for it: like native's look at what is waiting, they do not wait for the other end).

    A process, not a thread, because a thread cannot be stopped while it reads: Ctrl-C at a terminal kills the reader too (the terminal's process group), and at the end of the run a reader still reading is killed (RVM.StdinReader~stop, from endProgram; rvm.mjs before it exits), whereas the ooRexx host would wait for a thread that reads, and Node for a thread of its pool, until a line came.

  • rxsock: host sockets are always non-blocking and a call that would block on a socket the program considers blocking parks only its activity (RVM.SockWait, see libraries).

Everything else the host does synchronously blocks the whole RVM: other host I/O (files do not wait), and in Node a read of standard input where there is no worker (RVM_WORKER=0, the browser) or a pipe read with nothing else to run (it is read directly, as before: a reader for each chunk would cost a process each).

Design notes

  • Deterministic count-based slicing. The running activity keeps the machine until it waits, ends, or runs 10,000 clauses while another is ready. Switching is never driven by the clock, so the same input gives the same output in both hosts. A large slice makes short programs behave like native's most frequent interleaving (caller runs to the end after REPLY), and busy-waits such as do until m~completed; end still terminate. Native ooRexx switches about every 50 instructions (relinquishIfNeeded) and at I/O, so its order varies from run to run; tests must synchronise (locks, GUARD WHEN, RESULT) rather than rely on order.
  • No ready activity ends the run. Waiting activities at that point wait for something that cannot happen; native would hang forever. Ending with the main program's exit code turns a hang into a clean termination.
  • Hybrid clock. Timed waits conflict with "never by the clock". The real clock is the default so programs behave as users expect; the virtual clock (RVM_CLOCK=virtual) makes timer tests deterministic and instant and is what the oo test suite uses.
  • Green threads, not host threads. Neither host has usable shared-memory threads for Rexx objects; a single suspendable machine with explicit activities keeps both hosts identical and makes locks and REPLY explicit data (RVM.Pool, RVM.Level) ported from VariableDictionary and RexxActivation.
  • Natives return markers instead of blocking (RVM.Wait, RVM.StartMessage, RVM.Reraise): a native cannot be suspended in the middle of host code, so it gives up and is re-sent; semaphore results come back through waitResult.
  • The REPLY lock is queued immediately when it cannot be transferred, modelling native's almost-always outcome (the new thread requests the lock before the caller releases it).
  • Alarm/Ticker via LIBRARY REXX natives, not rewritten in Rexx: this mirrors native's structure (CoreClasses + TimeSupport natives) and the same mechanism serves the stream_*, file_* and RexxQueue methods.
  • UNINIT only at program end, marking from permanent roots. The RVM does no mid-run collection; running UNINIT at end with a mark from .environment reproduces native's lastChanceUninit without depending on host GC (and without WeakReference: see divergences). Creation order is used because it is stable.

Divergences from native

  • Inter-activity order is the RVM's deterministic one (accepted).
  • Waiting for something that cannot come ends the run instead of hanging.
  • Virtual clock: busy loops do not advance time; TIME/DATE include skipped time.
  • The clause where a HALT lands depends on timing in native (and on slicing in the RVM); the clause shown in the 4.1 report may differ between hosts.
  • UNINIT order is creation order (native: hash-table order) and never before the end (native: whenever GC runs).
  • Nested waits that cross: 93.900 (17).
  • A signal sent to the interpreter alone (not to its process group, as Ctrl-C at a terminal is) while an activity waits for a command that lets the others run (or, in the JS host, any command): native stops waiting for the command at once (RC is then undefined); the RVM waits for it to end, then the HALT (17).

Known gaps

  • In Node without its worker (RVM_WORKER=0) and in the browser, a read of standard input blocks every activity (Blocking operations).