Search⌘ K

Creating Threads

Explore how to create threads in Ruby using various Thread class methods like new, start, and fork. Understand thread states, status values such as run or sleep, and how thread priority affects execution. This lesson teaches you to manage Ruby threads effectively for concurrent programming.

We'll cover the following...

Creating Threads

We can create threads in Ruby using the following class methods of the Thread class:

  • new()

  • start()

  • fork()

Note that all these methods create and start the thread at the same time.

An example of creating a thread and passing arguments to it using the new() method is presented below.

Ruby
# Example to show how to span a thread using Thread.new
Thread.current.name = "mainThread"
# spawn a child thread
thread = Thread.new("Hello", "World") { |arg1, arg2|
Thread.current.name = "childThread"
puts("Name #{Thread.current.name} and id #{Thread.current.__id__} says #{arg1} #{arg2}")
}
# wait for the thread to finish
thread.join()
puts("Name #{Thread.current.name} and id #{Thread.current.__id__}")

On line#6, we use the ...