@head @module thread @title thread: Concurrent programming with threads
This module provides low-level facilities for using concurrent threads that are executed conceptually simultaneously. The Mutex and Condition classes can be used to synchronize threads and implement communication between threads.
Program execution starts in a special main thread. The execution of a program ends after the main thread ends. If any other threads are executing at program exit, they will be forcibly terminated. It is recommended that programs explicitly end threads by calling join to avoid data loss due to terminated threads.
Mutex objects are used for mutual exclusion, i.e. to make sure that only a single thread is accessing a resource such as an object, a variable or a file at the same time. Sometimes Mutex objects need to be used even though there is no obvious need for mutual exclusion. Therefore the rules below must be followed very carefully in any code that uses threads.
Each time a thread accesses a variable or an object, if that variable or object may have been modified by another thread since the creation of that thread, that access must be protected my a mutex. Likewise, the operations that actually modify the variable or the object must be protected by the same mutex.
For example, consider two simultaneous threads that call functions F1 and F2: @example var Shared = 1 def F1() Shared = 2 -- Error! end def F2() if Shared == 2 -- Error! DoSomething() end end @end
The function F2 accesses a variable that may have been modified by F1 in another thread. This in an error, and to remedy this, all the variable accesses must be protected by a mutex. @note As an exception, some classes may perform the required locking automatically. Unless this is explicitly mentioned, however, the caller must take care of locking. Remember that @ref{Stream} objects and their descendants do not typically perform any locking! @end