1 / 8

Multi-Treading Basics

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

avery
Download Presentation

Multi-Treading Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Multi-Treading Basics in Ruby

  2. 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()}

  3. 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

  4. 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

  5. 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.

  6. Multi-Thread Example #!/usr/bin/ruby defcalFib (x) if x <= 1 result = 1 else result = calFib(x-1) + calFib(x-2) end end

  7. 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

  8. Code Continued t1 = Thread.new{func1()} t2 = Thread.new{func2()} t1.join t2.join

More Related