如果我们谈论的是Ruby中的普通程序,那么所有语句都将按顺序执行,因为它曾经只有一个通常称为主线程的线程。但是我们的程序可能有多个线程,这个概念被称为多线程。多线程的优点是我们的程序使用更少的内存空间并共享相同的地址。借助这一概念,我们可以在同一时间执行多个任务。我们知道可以借助thread.new关键字创建一个新线程。
现在,让我们看看如何借助下面提供的示例创建多个线程:
=begin Ruby program to demonstrate multithreading =end def Nhooo1 a = 0 while a <= 10 puts "Thread execution: #{a}" sleep(1) a = a + 1 end end def Nhooo2 b = 0 while b <= 5 puts "Thread2: #{b}" sleep(2) b = b + 1 end end x = Thread.new{Nhooo1()} y = Thread.new{Nhooo2()} x.join y.join
输出结果
RUN 1: Thread execution: 0 Thread2: 0 Thread execution: 1 Thread execution: 2 Thread2: 1 Thread execution: 3 Thread execution: 4 Thread2: 2 Thread execution: 5 Thread execution: 6 Thread2: 3 Thread execution: 7 Thread execution: 8 Thread2: 4 Thread execution: 9 Thread execution: 10 Thread2: 5 RUN 2: Thread execution: 0 Thread2: 0 Thread execution: 1 Thread2: 1 Thread execution: 2 Thread execution: 3 Thread2: 2 Thread execution: 4 Thread execution: 5 Thread2: 3 Thread execution: 6 Thread execution: 7 Thread2: 4 Thread execution: 8 Thread execution: 9 Thread2: 5 Thread execution: 10
在上面的示例中,即使程序没有变化,您也可以观察到两个输出都是不同的。这是因为线程的执行是基于它们的优先级执行的,并且默认情况下,所有线程都具有相同的优先级。它们的执行取决于指针。您还可以观察到两个线程同时执行。
线程也可以在程序中使用相同的资源,请参考以下示例,
=begin Ruby program to demonstrate multithreading using same resource =end $g_var = 10 def Nhooo1 a = 0 while a <= 10 puts "Thread execution: #{a}" sleep(1) a = a + 1 end puts "Inside Thread 1 ; #{$g_var+19}" end def Nhooo2 b = 0 while b <= 5 puts "Thread2: #{b}" sleep(2) b = b + 1 end puts "Inside Thread 2 ; #{$g_var+10}" end x = Thread.new{Nhooo1()} y = Thread.new{Nhooo2()} x.join y.join
输出结果
Thread execution: 0 Thread2: 0 Thread execution: 1 Thread execution: 2 Thread2: 1 Thread execution: 3 Thread2: 2 Thread execution: 4 Thread execution: 5 Thread2: 3 Thread execution: 6 Thread execution: 7 Thread2: 4 Thread execution: 8 Thread execution: 9 Thread2: 5 Thread execution: 10 Inside Thread 1 ; 29 Inside Thread 2 ; 20
在上面的代码中,您可以观察到存在一个名为$g_var的全局变量名称。两个线程都可以访问它,但是当它们操纵它的值时,它不会对其他线程操纵的值产生任何影响。