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:zh [2023/10/20 11:38]
hfsr [Thread API]
api:thread:zh [2023/10/20 13:20] (current)
hfsr [Thread Yield/Pull Without Blocking Example]
Line 129: Line 129:
  
  
-===== Thread Handle ​API =====+===== 线程句柄API =====
  
 - `t:​resume():​ boolean, string` - `t:​resume():​ boolean, string`
  
-  ​Resumes (or thaws) a suspended thread. Returns success and an error message on failure. A thread begins its life already in a running state and thus basic thread workflows will not ever need to call `t:​resume()`. A "​running"​ thread will autonomously continue until it completes. ​`t:resume()` is only necessary to resume a thread that has been suspended(`t:suspend()`). **Note** that because you are not directly resuming the thread any exceptions thrown from the thread are absorbed by the threading library and not exposed to your process.+  ​恢复(或者说解冻)一个暂停的线程。返回操作是否成功,若失败额外返回一条报错信息。线程在创建时直接就是运行状态,因此在基本的线程工作流程中完全用不到调用`t:​resume()`。“运行中”的线程会自动继续,直到执行完毕。只有在需要恢复被暂停的(`t:suspend()`)线程时才需要`t:resume()`**请注意,**因为你不是直接恢复线程,线程抛出的一切异常都会被线程运行库吸收,不会暴露给你的进程。
  
-  * At this time there is no way to hook in an exception handler for threads but for now `event.onError` ​is used to print the error message to "/​tmp/​event.log"​. Please note that currently the hard interrupt exception is only thrown once, and the behavior of a process with threads when a hard interrupt is thrown is unspecified. At this time, any one of the threads or the parent process may take the exception. These details are not part of the specification for threads and any part of this implementation detail may change later.+  * 目前还无法为线程挂载异常处理函数,但是现在可以用`event.onError`将报错信息输出到"/​tmp/​event.log"​。请注意目前硬中断异常只会抛出一次,并且在抛出硬中断时,带线程的进程执行的行为仍未指定。目前,任何一个线程或父进程都可能接收到异常。这些细节并不是线程规范的一部分,任何实现细节的部分都可能在以后发生变化。
  
 - `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. 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.+  ​暂停(或者说冻结)一个运行中的线程。返回操作是否成功,若失败额外返回一条报错信息。“暂停的”线程不会自动唤醒,也不会随其父进程(若附有的话)结束而结束。暂停的线程会忽略出现的事件,代表此线程中定义的任何事件侦听器和定时器都不会响应事件通知。请注意线程不会缓存事件信号,暂停的线程可能会错失其等待的信号。例如,假设一个线程最近一次使用了`event.pull("​modem_message"​)`等待信号,并且被“暂停”了,此时电脑收到了一条"​modem_message"​。这样线程将错失事件,永远不知道发生了什么。请注意如果你暂停了一条正在被阻塞以等待事件的线程,线程下次被唤醒时会接收到什么事件是未指定的。
   ​   ​
-  ​Suspending the current thread causes the thread to immediately ​yield and does not resume until `t:​resume()` ​is called explicitly elsewhere.+  ​暂停当前线程就会导致线程立刻yield,在其他地方显式调用`t:​resume()`之前也不会恢复。
  
-**Special notes about `t:resume``t:​suspend`**+**`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 these examples:+不要把这两个方法当作`coroutine.resume()``coroutine.yield()`。这两个方法是间接的,而且线程是独自异步开始或停止运行的。请将这一特性与协程方法相对比,协程方法是直接的,而且会立即唤起或离开协程的执行。参考这些样例:
  
 ```lua ```lua
 local thread = require("​thread"​) local thread = require("​thread"​)
-local t -- this example needs an upvalue to t+local t -- 此样例需要t的upvalue
 t = thread.create(function() t = thread.create(function()
   print("​start"​)   print("​start"​)
Line 159: Line 159:
 ``` ```
  
-Output:+输出:
 ``` ```
 start start
Line 179: Line 179:
 ``` ```
  
-Output:+输出:
 ``` ```
 start start
Line 190: Line 190:
 - `t:kill()` - `t:kill()`
  
-  ​Stabby stab! Kills the thread dead. The thread is terminated and will not continue its thread function. Any event registrations it made will die with it. Keep in mind that the core underlying ​Lua type is a coroutine which is not a preemptive thread. Thus, the thread'​s stopping points are deterministic,​ meaning that you can predict exactly where the thread will stop. Consider this example:  +  ​给它一刀!将线程杀死。线程将会被终止,不能再继续执行其线程函数。它的所有事件注册记录也都会随之结束。请注意核心底层实际上是Lua协程,协程不是抢占式线程。因此线程的结束点是可知的,意味着你可以预测线程结束的准确位置。参考此样例:
  
 ```lua ```lua
Line 209: Line 208:
 ``` ```
  
-Output:+输出:
 ``` ```
 running running
Line 219: Line 218:
 - `t:​status():​ string` - `t:​status():​ string`
  
-  ​Returns the thread status as a string.+  ​以字符串形式返回线程状态。
  
-  * **"​running"​**+  * **"​running" ​运行**
  
-  ​A running thread will continue (autonomously reactivating) after yields and blocking calls until its thread function exits. This is the default and initial state of a created thread. A thread remains in the "​running"​ state even when blocked or not active. A running thread can be suspended(`t:​suspend()`) or killed (`t:kill()`) but not resumed(`t:​resume()`). A running thread will block calls to `t:​join()` ​and block its parent from closing. Unlike a coroutine which appears "​suspended"​ when not executing in this very moment, a thread state remains "​running"​ even when waiting for an event.+  ​运行中的线程会在yield和阻塞式调用后继续运行(自动重新开始活动),直到其线程函数退出。这是创建后线程的初始与默认状态。线程就算在阻塞或不活动的状态下也会保持“运行”状态。运行中的线程可以被暂停(`t:​suspend()`)或杀死(`t:kill()`),但是不可以恢复(`t:​resume()`)。运行中的线程将会阻塞`t:join()`的调用,也会阻塞其父进程的关闭。与协程不同,协程在未执行时即为“暂停”状态,而线程就算在等待事件时也是“运行”状态。
  
-  * **"​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 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()`).+  ​被暂停的线程会保持暂停状态,永远不会自动恢复执行其线程函数。暂停的线程会在其附着的父进程关闭时或你试图`t:join()`它时自动被杀死。暂停的线程会忽略事件信号,此线程的上下文所创建的,或其创建的任何子线程所创建的事件注册记录,也都会忽略事件信号。暂停线程的子线程表现会与暂停一样,即使其状态为“运行”。暂停的线程可以恢复(`t:​resume()`)或者杀死(`t:kill()`),但不可以暂停(`t:​suspend()`)。
  
-  * **"​dead"​**+  * **"​dead" ​死亡**
  
-  ​A dead thread has completed or aborted its execution or has been terminated. It cannot be resumed(`t:​resume()`) nor suspended(`t:​suspend()`). A dead thread does not block a parent process from closing. Killing a dead thread is not an error but does nothing.+  ​死亡的线程是结束了或放弃了自己的运行或被终止的线程。它不可被恢复(`t:​resume()`)也不可被暂停(`t:​suspend()`)。死亡的线程不会阻塞父进程的关闭。杀死死亡的线程不会报错,而是什么也不做。
  
-** Status Examples ​**+** 状态样例 ​**
  
 ```lua ```lua
Line 245: Line 244:
 ``` ```
  
-Output:+输出:
 ``` ```
 before sleep before sleep
Line 268: Line 267:
 ``` ```
  
-Output:+输出:
 ``` ```
 before sleep before sleep
Line 279: Line 278:
 - `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, ​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). +  ​将一个线程附着到一个进程,通常称为子线程或附着线程。`level`为可选参数,可用于获取父进程,传递0或`nil`则使用当前运行进程。在最初创建线程时,线程已经被附着于当前进程。若`level`指向了不存在的线程,则此方法会返回`nil`与一条报错信息,否则返回true。附着的线程将会阻塞其父进程的关闭,直到线程死亡(或者被杀死,或者父进程放弃执行)。 
 +  
 - `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). A detached thread will continue to run until the computer is shutdown or rebooted, or the thread dies.+  ​将一个线程从其父进程(若有)上解除附着。若未执行动作则返回`nil`与一条报错信息,否则返回自身(以便于你想在同一行中创建一个线程并将其解除附着)。解除附着的线程会继续执行,直到电脑关机或重启,或者线程死亡。
  
 ```lua ```lua
Line 291: Line 290:
 - `t:​join([timeout:​ number]): boolean, string` - `t:​join([timeout:​ number]): boolean, string`
  
-  ​Blocks the caller until `t` is no longer running or (optionally) returns false if `timeout` ​seconds is reached. After a call to `t:​join()` ​the thread state is "​dead"​. Any of the following circumstances allow `join` ​to finish and unblock the caller+  ​阻塞调用者,直到`t`不再运行。或者在到达了`timeout`秒的超时时间后返回`false`(可选)。在`t:join()`的调用结束后线程的状态将为“死亡”。任一下列情况都会导致`join`结束并停止阻塞调用者:
  
-  * The thread continues running until it returns from its thread function +  * 线程继续运行,直到其从线程函数中返回。 
-  * The thread aborts, or throws an uncaught exception +  * 线程被放弃,或抛出了未被捕获的异常。 
-  * The thread is suspended +  * 线程被暂停。 
-  * The thread is killed+  * 线程被杀死
  
-  ​Calling ​`thread.waitForAll({t})` ​is functionally equivalent to calling ​`t:join()`. When a processs is closing it will call `thread.waitForAll` ​on the group of its child threads if it has any. A child thread blocks its parent thread by the same machanism.+  ​调用`thread.waitForAll({t})`在功能上与调用`t:join()`一致。在进程结束时会对其子线程调用`thread.waitForAll`(若有)。子线程也通过同样的机制阻塞其父进程。
  
-===== Thread Exception Example ​=====+===== 线程异常样例 ​=====
  
-This example demonstrates what happens when a thread throws an exception. A thread stops executing and becomes "​dead"​ when it throws an uncaught exception. The exception message is not printed to stdout ​nor stderr ​(see `t:​resume()`) for details. ​+此样例演示了线程抛出异常时会发生什么。线程在抛出未捕获的异常时会停止执行并进入“死亡”状态。报错信息将不会输出到stdoutstderr(详见`t:​resume()`)。 ​
  
 ```lua ```lua
Line 311: Line 310:
 local reader = thread.create(function() local reader = thread.create(function()
   print("​reader start"​)   print("​reader start"​)
-  error("​thread abort"​) -- throws an exception+  error("​thread abort"​) -- 抛出一个异常
   print("​reader done")   print("​reader done")
 end) end)
Line 317: Line 316:
 ``` ```
  
-Output+输出:
 ``` ```
 p start p start
Line 324: Line 323:
 ``` ```
  
-===== Thread Interrupt Handler Example ​=====+===== 线程中断处理函数样例 ​=====
  
-This example demonstrates how you would register a function that handles soft interrupts (^c) to close file handles, release resources, etc, and then exit the whole program.+此样例演示了你该如何注册处理软中断(^c)的函数,用于关闭文件句柄、释放资源等等,然后退出整个程序。
  
 ```lua ```lua
Line 346: Line 345:
  
 thread.waitForAny({cleanup_thread,​ main_thread}) thread.waitForAny({cleanup_thread,​ main_thread})
-os.exit(0) -- closes all remaining threads+os.exit(0) -- 关闭所有剩余线程
 ``` ```
  
-Assuming the user presses ​^c to send an interrupt +假设用户按下了^c发送了一次软中断 
-Output+ 
 +输出:
 ``` ```
 main program main program
Line 357: Line 357:
 ``` ```
  
-===== Thread ​Yield/​Pull ​Without Blocking Example ​=====+===== 非阻塞式线程Yield/Pull操作样例 ​=====
  
-This example demonstrates that now OpenOS ​supports non blocking threads.+此样例演示了现在OpenOS可支持非阻塞式线程。
  
 ```lua ```lua
Line 375: Line 375:
 ``` ```
  
-Output+输出:
 ``` ```
 custom_event_a custom_event_a