📅  最后修改于: 2021-01-08 13:22:09             🧑  作者: Mango
线程表示轻量级子进程。这是一条单独的执行路径。在Ruby中,可以通过使用多个线程拆分程序中的任务或使用多个进程在不同程序之间拆分任务来同时运行程序的不同部分。
线程是并发编程模型的Ruby实现。
普通程序只有一个执行线程。程序中的所有语句均按顺序执行。
多线程程序中包含多个执行线程。它使用较少的内存空间并共享相同的地址空间。多线程用于一次执行多个任务。
使用thread.new调用创建一个新线程。它与主线程的执行不同。
为了创建一个新线程,Ruby提供了三个关键字,分别是:: new,:: start和:: fork。
要启动新线程,请将代码块与对Thread.new,Thread.start或Thread.fork的调用相关联。线程将被创建。块退出时,新线程退出。
句法:
# Original thread runs
Thread.new {
# New thread is created.
}
# Original thread runs
在Ruby中终止线程有多种方法。要退出给定线程,请使用:: kill类。
句法:
thr = Thread.new { ... }
Thread.kill(thr)
#!/usr/bin/ruby
th = Thread.new do #Here we start a new thread
Thread.current['counter']=0
5.times do |i| #loop starts and increases i each time
Thread.current['counter']=i
sleep 1
end
return nil
end
while th['counter'].to_i < 4 do
=begin
th is the long running thread
and we can access the same variable
from inside the thread here
=end
puts "Counter is #{th['counter']}"
sleep 0.5
end
puts "Long running process finished!"
输出:
创建线程后,无需启动它。获得适当的CPU资源后,它将自动运行。块中的最后一个表达式是线程的值。如果线程已完全运行,则value方法返回线程值,否则value方法将阻塞它并在线程完成后返回。线程类在运行查询和操作线程时定义了许多方法。
通过调用线程的Thread.join方法,您可以等待特定线程完成。
线程中可能有一些例外。如果在除主线程之外的任何其他线程中出现异常,则取决于abort_on_exception。默认情况下,此选项始终为false。这意味着未处理的异常将静默终止线程。可以通过将abort_on_exception = true或$ DEBUG设置为true来更改此设置。
要处理异常,可以使用类方法:: handle_interrupt 。它将与线程异步处理异常。
线程是用块创建的。在块中创建的局部变量只能由存在该块的线程访问。
Ruby线程类允许按名称创建和访问线程局部变量。线程对象被视为哈希,使用[] =编写元素,然后使用[]读回它们。
Ruby通过在程序中使用:: stop和:: pass方法来支持调度线程。
:: stop类方法使当前正在运行的线程进入睡眠状态并安排另一个线程的执行。线程进入睡眠状态后,将使用实例方法唤醒将线程标记为可进行调度。
:: pass类方法尝试将执行传递给另一个线程。运行线程是否会切换取决于操作系统。
线程优先级提示根据线程的优先级调度线程。高优先级线程首先被调度。它还取决于操作系统。线程可以在执行第一个操作时增加或减少其自身的优先级。
Ruby线程排除法指出,当两个线程共享同一数据并且其中一个线程修改该数据时,我们需要确保没有线程可以看到彼此处于不一致状态的数据。例如,银行服务器。一个线程负责帐户中的汇款,另一个线程正在为客户生成月度报告。
Method | Description |
---|---|
abort_on_exception | It returns the status of global “abort on exception” condition. The default is true. When it is set to true, all threads will abort if an exception is raised in any thread. |
abort_on_exception= | When it is set to true, all threads will abort if an exception is raised. It returns the new state. |
current | It returns the currently executing thread. |
exclusive{block} | It wraps the block in a single, returning the value of the block. |
exit | It terminates the currently running thread and schedules another thread tro run. |
kill(thread) | It causes the given thread to exit. |
fork([args]*){|args| block} | It is basically same as ::new method. |
handle_interrupt(hash){…} | Changes asynchronous interrupt timing. |
list | Returns an array of thread objects for all threads that are either runnable or stopped. |
main | Returns the main thread. |
new{…}/ new(*args, &proc)/ new(*args){|args|…} | It creates a new thread executing the given block. |
pass | It gives the thread scheduler a hint to pass execution to another thread. A running thread may or may not switch depending upon the OS. |
pending_interrupt?(error = nil) | It returns whether or not the asynchronous queue is empty. |
start([args]*){|args|block} | It is basically same as ::new method. |
stop | It stops execution of the current thread, putting it into ‘sleep’ state and schedules execution of another thread. |
Method | Description |
---|---|
thr[sym] | It returns the value of a fiber-local variable using either a string or symbol name. |
thr[sym]= | It creates the value of a fiber-local variable using either a string or symbol name. |
abort_on_exception | It returns status of “abort on exception” for thr. |
abort_on_exception= | When set to true, all threads will abort if an exception is raised in this thr. |
add_trace_func(proc) | Adds proc as a handler for tracing. |
alive? | It returns true if thr is running or sleeping. |
backtrace | It returns current backtrace of target ahead. |
backtrace_locations(*args) | It returns the execution stack for the target ahead. |
exit/kill/terminate | It terminates thr and executes another thread to run. |
group | It returns the ThreadGroup which contains the given thread or returns nil. |
inspect | It dumps the name, id and status of thr to a string. |
join | The calling thread will suspend execution and run this thr. |
key?(sym) | It returns true if the given string exists as a fiber-local variable. |
keys | It returns an array of the name of the fiber-local variables. |
pending_interrupt?(error=nil) | Returns whether or not the asynchronous queue is empty for the target thread. |
priority | It returns the priority of thr. |
priority= | It sets the priority of thr to integer. |
kill | It works same as exit. |
raise | It raises an exception from the given thread. |
run | It wakes up thr, making it eligible for scheduling. |
safe_level | It returns the safe level in effect for thr. |
set_trace_func(proc) | It establishes proc on thr as the handler. |
status | It returns the status of thr. |
stop? | It returns true if thr is sleeping or dead. |
terminate | It terminates thr and schedules another thread to run. |
thread_variable?(key) | It returns true if the given string exists as a thread local variable. |
thread_variable_get(key) | It returns the value of a thread local variable that has been set. |
thread_variable_set(key, value) | Set a thread local with key to value. |
thread_variable | It returns an array of the thread-local variables. |
value | It waits for thr to complete, using join and returns its value. |
wakeup | Makes a given thread eligible for scheduling, although it may still remained block on I/O. |