Multithreading with Threads

The lowest-level mechanism in Ruby for doing two things at once is to use the Thread class. Although threads can in theory take advantage of multiple processors or multiple cores in a single processor, there’s a major catch. Many Ruby extension libraries aren’t thread-safe because they expect to be protected by the GIL. So, Ruby uses native operating system threads but operates only a single thread at a time. Unless you use the Ractor library, you’ll never see two threads in the same application running Ruby code truly concurrently. You’ll instead see threads that are busy executing Ruby code while another thread waits on an I/O operation.

Creating Ruby Threads

The code that follows is a simple example. It downloads ...

Get Programming Ruby 3.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.