80 likes | 225 Views
Multi-Treading Basics. in Ruby. Creating new Threads. To start a new thread in Ruby a code block needs to only be associated with the call Thread.new The new Thread executes the given code block and immediately returns to the original thread and continues execution
E N D
Multi-Treading Basics in Ruby
Creating new Threads • To start a new thread in Ruby a code block needs to only be associated with the call Thread.new • The new Thread executes the given code block and immediately returns to the original thread and continues execution • t1 = Thread.new{func1()} • t2 = Thread.new{func2()}
Exception Handling • If an exception occurs in the main thread and is not handled the interpreter will print the exception message and exits. Killing all treads running. • When multi-threading in ruby unhandled exceptions can pass from one thread to another so it is important to handle any exceptions that may occur
Exception Handling cont. • To handle exceptions that may occur in your threads you can simply use the thread.abort_on_exception setting • Simply set this to true or false. Setting it to false will cause the current thread to be killed while allowing all other threads to continue to run. Setting it to true will cause all treads to exit • t1 = Thread.new{func1()} t1.about_on_exception = true
Variables Access • An important thing to consider when multi threading is what variables your thread will need access to. Threads will have access to all variables that are in the scope when the thread is created.
Multi-Thread Example #!/usr/bin/ruby defcalFib (x) if x <= 1 result = 1 else result = calFib(x-1) + calFib(x-2) end end
Code Continued def func1 i = 0 while i<=20 result = calFib(i) puts"Thefibonacci of #i is #result" sleep(2) i=i+1 end end def func2 j=21 while j<= 40 result2 = calFib(j) puts "The Fibonacci of #j is #result2" sleep(2) j=j+1 end end
Code Continued t1 = Thread.new{func1()} t2 = Thread.new{func2()} t1.join t2.join