如何在 Ruby 中实现多线程


在本文中,我们将了解如何在 Ruby 中使用多线程。我们将举几个例子,在这些例子中,我们将生成两个新线程,然后对它们执行一些并发操作。在 Ruby 中,我们可以借助Thread.new() 函数创建一个新线程。

示例 1

请看以下示例,了解多线程的本质以及它们在 Ruby 中如何执行。

Open Compiler
#!/usr/bin/ruby # first method def First_Method a = 0 while a <= 5 puts "Thread1: #{a}" # pause the execution of the current thread sleep(1) # incrementing the value of a a = a + 1 end end # Second method def Second_Method b = 0 while b <= 3 puts "Thread2: #{b}" # Pause the execution of the current thread sleep(0.5) # incrementing the value of b b = b + 1 end end x = Thread.new{First_Method()} y = Thread.new{Second_Method()} # using Thread.join x.join y.join puts "End"

输出

在执行时,它将产生以下输出

Tuts1: 0
Tuts2: 0
Tuts2: 1
Tuts1: 1
Tuts2: 2
Tuts2: 3
Tuts1: 2
Tuts1: 3
Tuts1: 4
Tuts1: 5
End

在此示例中,我们考察了两个线程以及它们如何在两者之间进行上下文切换。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

现在让我们看一下如何在函数之间定义一些日志以显示线程的范围。考虑如下所示的代码。

Open Compiler
#!/usr/bin/ruby $str = "Learn To Code in Ruby" # first method def First_Method a = 0 while a <= 5 puts "Thread1: #{a}" # pause the execution of the current thread sleep(1) # incrementing the value of a a = a + 1 end puts "Global variable: #$str" end # Second method def Second_Method b = 0 while b <= 3 puts "Thread2: #{b}" # pause the execution of the current thread sleep(0.5) # incrementing the value of b b = b + 1 end puts "Global variable: #$str" end x = Thread.new{First_Method()} y = Thread.new{Second_Method()} # using Thread.join x.join y.join puts "End"

输出

在执行时,它将产生以下输出

Thread1: 0
Thread2: 0
Thread2: 1
Thread1: 1
Thread2: 2
Thread2: 3
Thread1: 2
Global variable: Learn To Code in Ruby
Thread1: 3
Thread1: 4
Thread1: 5
Global variable: Learn To Code in Ruby
End

更新于: 2022 年 4 月 12 日

210 次浏览

开启你的 职业

完成课程获得认证

开始
广告