Creating Threads

This lesson discusses the various ways in which we can create, run, prioritise and check the status of threads.

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.

Press + to interact
# 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__}")
...