13.1. Creating and Manipulating Threads

The most basic operations on threads include creating a thread, passing information in and out, stopping a thread, and so on. We can also obtain lists of threads, check the state of a thread, and check various other information.

We present an overview of these basic operations here.

13.1.1. Creating Threads

Creating a thread is easy. Simply call the new method and attach a block that will be the body of the thread.

thread = Thread.new do
  # Statements comprising
  #   the thread...

The value returned is obviously an object of type Thread. This is usable by the main thread to control the thread it has created.

What if we want to pass parameters into a thread? We can do this by passing parameters into Thread.new ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.