[top] [prev] [next]

The Thread interface

If a shared variable is written concurrently by two threads, or written by one and read concurrently by another, the effect is to set the variable to an implementation-dependent value of its type. For example, if one thread writes a[0] while another concurrently writes a[1], one of the writes might be lost. Thus, portable programs must use the Thread interface to provide mutual exclusion for shared variables.

INTERFACE Thread;

TYPE
  T <: REFANY;
  Mutex =  MUTEX;
  Condition <: ROOT;
  Closure = OBJECT METHODS apply(): REFANY END;
A Thread.T is a handle on a thread. A Mutex is locked by some thread, or unlocked. A Condition is a set of waiting threads. A newly-allocated Mutex is unlocked; a newly-allocated Condition is empty. It is a checked runtime error to pass the NIL Mutex, Condition, or T to any procedure in this interface.

PROCEDURE Fork(cl: Closure): T;
A handle on a newly-created thread executing cl.apply().

PROCEDURE Join(t: T): REFANY;
Wait until t has terminated and return its result. It is a checked error to call this more than once for any t.

PROCEDURE Wait(m: Mutex; c: Condition);
The calling thread must have m locked. Atomically unlocks m and waits on c. Then relocks m and returns.

PROCEDURE Acquire(m: Mutex);
Wait until m is unlocked and then lock it.

PROCEDURE Release(m: Mutex);
The calling thread must have m locked. Unlocks m.

PROCEDURE Broadcast(c: Condition);
All threads waiting on c become eligible to run.

PROCEDURE Signal(c: Condition);
One or more threads waiting on c become eligible to run.

PROCEDURE Self(): T;
Return the handle of the calling thread.

EXCEPTION Alerted;
Used to approximate asynchronous interrupts.

PROCEDURE Alert(t: T);
Mark t as an alerted thread.

PROCEDURE TestAlert(): BOOLEAN;
TRUE if the calling thread has been marked alerted.

PROCEDURE AlertWait(m: Mutex; c: Condition) RAISES {Alerted};
Like Wait, but if the thread is marked alerted at the time of call or sometime during the wait, lock m and raise Alerted.

PROCEDURE AlertJoin(t: T): REFANY RAISES {Alerted};
Like Join, but if the calling thread is marked alerted at the time of call or sometime during the wait, raise Alerted.

CONST
  AtomicSize = ...;
An implementation-dependent integer constant: the number of bits in a memory-coherent block. If two components of a record or array fall in different blocks, they can be accessed concurrently by different threads without locking.

END Thread.

The CM Modula-3 version of Thread is here.

[top] [prev] [next]