Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
api:thread [2017/06/11 10:14]
vexatos
api:thread [2019/12/06 14:15] (current)
jasonc [Thread API]
Line 2: Line 2:
 The Thread API provides a variation of coroutines for openos. A thread is superior to basic coroutines in many ways and, for many workflows, is easier to work with. An openos thread is an autonomous non-blocking detachable process. The Thread API provides a variation of coroutines for openos. A thread is superior to basic coroutines in many ways and, for many workflows, is easier to work with. An openos thread is an autonomous non-blocking detachable process.
  
-* **Autonomous**:​ Threads asynchronously begin execution immediately after creation without needing to call resume. Unlike coroutines, threads self-resume after yielding and do not yield back to the line of code where they were created. Programming with coroutines builds on the cooperative yield and resume calls made explicitly by the user. Yielding or calling `event.pull` from a thread, however, only temporarily blocks just that thread and continue on its own.+* **Autonomous**:​ Threads asynchronously begin execution immediately after creation without needing to call resume. Unlike coroutines, threads self-resume after yielding and do not yield back to the line of code where they were created. Programming with coroutines builds on the cooperative yield and resume calls made explicitly by the user. Yielding or calling `event.pull` from a thread, however, only temporarily blocks just that thread and will continue on its own.
  
  
-* **Non-Blocking**:​ Threads can call `computer.pullSignal` (or any higher level wrapper such as `event.pull`,​ `io.pull`, etc) without blocking the main kernel process nor any other thread. The thread itself is blocked until a signal or timeout occurs. The computational flow of the thread behaves just as if the same code where run in a script from the command line. Behind the scenes, the thread library is using pullSignal to swap between threads, and waking threads up when appropriate. This is very much unlike coroutines where `computer.pullSignal` blocks all other activity on the system until a signal or timeout occurs.+* **Non-Blocking**:​ Threads can call `computer.pullSignal` (or any higher level wrapper such as `event.pull`,​ `io.pull`, etc) without blocking the main kernel process nor any other thread. The thread itself is blocked until a signal or timeout occurs. The computational flow of the thread behaves just as if the same code were run in a script from the command line. Behind the scenes, the thread library is using pullSignal to swap between threads, and waking threads up when appropriate. This is very much unlike coroutines where `computer.pullSignal` blocks all other activity on the system until a signal or timeout occurs.
  
  
Line 19: Line 19:
   * The thread is manually suspended. see `t:​suspend()`   * The thread is manually suspended. see `t:​suspend()`
  
 +====Event Registration Independence====
 +
 +A thread maintains an independent set of event registrations;​ it does not inherit any and it does not share any. Any event registration made (e.g. listeners or timers) inside a thread belongs to that thread.
 +  * When a thread dies all of its event registrations die with it.
 +  * A `suspended` thread ignores events (see `t:status() suspended`)
 +  * A thread cannot access/​remove/​interfere with another thread'​s event registrations.
 +  * A pushed event is observed by all running threads on the system.
 +  * Two separate threads can `event.pull` for the same event, and each thread will observe the event independently.
 ===== Overview ===== ===== Overview =====
  
Line 114: Line 122:
 ``` ```
  
-Please note that threads resume order is not specified+Please note that threads resume order is not specified ​and this example may print "​D"​ before it prints "Main program end" 
 + 
 +- `thread.current():​ table` 
 + 
 +  Returns the current thread `t` object. The init process does not represent a thread and nothing is returned from this method if called from the init process and not inside any thread. 
 + 
  
 ===== Thread Handle API ===== ===== Thread Handle API =====
Line 126: Line 140:
 - `t:​suspend():​ boolean, string` - `t:​suspend():​ boolean, string`
  
-  Suspends (or freezes) a running thread. Returns success and an error message on failure. A "​suspended"​ thread never autonomously wakes up and dies as soon as its parent process (if attached) closes. A suspended thread ignores events. That means any event listeners or timers created inside the thread will not respond to event notifications. Note that threads do not buffer event signals and a suspended thread may miss event signals it was waiting for. For example, if a thread was last waiting on `event.pull("​modem_message"​)` and is "​suspended"​ and a "​modem_message"​ is received by the computer then the thread will miss the event and never know it happened.+  Suspends (or freezes) a running thread. Returns success and an error message on failure. A "​suspended"​ thread never autonomously wakes up and dies as soon as its parent process (if attached) closes. A suspended thread ignores events. That means any event listeners or timers created inside the thread will not respond to event notifications. Note that threads do not buffer event signals and a suspended thread may miss event signals it was waiting for. For example, if a thread was last waiting on `event.pull("​modem_message"​)` and is "​suspended"​ and a "​modem_message"​ is received by the computer then the thread will miss the event and never know it happened. Please note that if you suspend a thread that is blocked waiting for an event, it is unspecified which event the thread will receive when it is next resumed. 
 +   
 +  Suspending the current thread causes the thread to immediately yield and does not resume until `t:​resume()` is called explicitly elsewhere.
  
 **Special notes about `t:resume`, `t:​suspend`** **Special notes about `t:resume`, `t:​suspend`**
  
-Do not think of these methods as `coroutine.resume()` nor `coroutine.yield()`. These methods are indirect and a thread will asynchronously start or stop running on its own. Contrast this to coroutine methods which directly and immediately invoke execution or leave execution of a coroutine. Consider ​this example:+Do not think of these methods as `coroutine.resume()` nor `coroutine.yield()`. These methods are indirect and a thread will asynchronously start or stop running on its own. Contrast this to coroutine methods which directly and immediately invoke execution or leave execution of a coroutine. Consider ​these examples:
  
 ```lua ```lua
Line 137: Line 153:
 t = thread.create(function() t = thread.create(function()
   print("​start"​)   print("​start"​)
-  ​t:suspend()+  ​thread.current():suspend()
   print("​after suspend"​)   print("​after suspend"​)
   os.sleep()   os.sleep()
Line 147: Line 163:
 ``` ```
 start start
 +```
 +
 +```lua
 +local thread = require("​thread"​)
 +local t -- this example needs an upvalue to t
 +t = thread.create(function()
 +  print("​start"​)
 +  thread.current():​suspend()
 +  print("​after suspend"​)
 +  os.sleep()
 +  print("​after sleep"​)
 +end)
 +print("​outside thread create"​)
 +t:resume()
 +print("​after resume"​)
 +```
 +
 +Output:
 +```
 +start
 +outside thread create
 after suspend after suspend
 +after resume
 +after sleep
 ``` ```
  
Line 189: Line 228:
   * **"​suspended"​**   * **"​suspended"​**
  
-  A suspended thread will remain suspended and never self resume execution of its thread function. A suspended thread is automatically killed when its attach ​parent closes or when you attempt to `t:join()` it. A suspended thread ignores event signals, and any event registrations made from the context of the thread, or any child threads created therein, also ignore any event signals. A suspended thread'​s children behave as if suspended even if their status is "​running"​. A suspended thread can be resumed(`t:​resume()`) or killed (`t:​kill()`) but not suspended(`t:​suspend()`).+  A suspended thread will remain suspended and never self resume execution of its thread function. A suspended thread is automatically killed when its attached ​parent closes or when you attempt to `t:join()` it. A suspended thread ignores event signals, and any event registrations made from the context of the thread, or any child threads created therein, also ignore any event signals. A suspended thread'​s children behave as if suspended even if their status is "​running"​. A suspended thread can be resumed(`t:​resume()`) or killed (`t:​kill()`) but not suspended(`t:​suspend()`).
  
   * **"​dead"​**   * **"​dead"​**
Line 241: Line 280:
 - `t:​attach([level:​ number]): boolean, string` - `t:​attach([level:​ number]): boolean, string`
  
-  Attaches a thread to a process, conventionally known as a child thread or attached thread. `level` is an optional used to get parent processes, 0 or nil uses the currently running process. When initially created a thread is already attached to the current process. This method returns nil and an error message if `level` refers to a nonexistent process, otherwise it returns truthy.+  Attaches a thread to a process, conventionally known as a child thread or attached thread. `level` is an optional used to get parent processes, 0 or nil uses the currently running process. When initially created a thread is already attached to the current process. This method returns nil and an error message if `level` refers to a nonexistent process, otherwise it returns truthy. An attached thread blocks its parent process from closing until the thread dies (or is killed, or the parent process aborts).
  
 - `t:​detach():​ table, string` - `t:​detach():​ table, string`
  
-  Detaches a thread from its parent if it has one. Returns nil and an error message if no action was taken, otherwise returns self (handy if you want to create and detach a thread in one line).+  Detaches a thread from its parent if it has one. Returns nil and an error message if no action was taken, otherwise returns self (handy if you want to create and detach a thread in one line). A detached thread will continue to run until the computer is shutdown or rebooted, or the thread dies.
  
 ```lua ```lua
Line 276: Line 315:
   print("​reader done")   print("​reader done")
 end) end)
-print("​p end", ​t:status())+print("​p end", ​reader:status())
 ``` ```
  
Line 324: Line 363:
  
 ```lua ```lua
 +local event = require("​event"​)
 local thread = require("​thread"​) local thread = require("​thread"​)
 thread.create(function() thread.create(function()