如何在 Ruby 中實現多執行緒
在本文中,我們將瞭解如何在 Ruby 中使用多執行緒。我們將舉幾個例子,在這些例子中,我們將生成兩個新執行緒,然後對它們執行一些併發操作。在 Ruby 中,我們可以藉助Thread.new() 函式建立一個新執行緒。
示例 1
請看以下示例,瞭解多執行緒的本質以及它們在 Ruby 中如何執行。
#!/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
在此示例中,我們考察了兩個執行緒以及它們如何在兩者之間進行上下文切換。
示例 2
現在讓我們看一下如何在函式之間定義一些日誌以顯示執行緒的範圍。考慮如下所示的程式碼。
#!/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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP