How to get output from a thread

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the concurrency category.

Last Updated: 2024-04-25

My first naive approach was this

t = Thread.new { sleep(10);  "c" }
#<Thread:0x00007fb88849f488@(pry):1 sleep>
res = t.join
#<Thread:0x00007fb88849f488@(pry):1 dead>

Unfortunately this just returned the thread object, now dead.

A similar lack of return values to join exists in another languages, e.g. Python.

Anyway, the simplest general way to get a thread to return values is to store thread-local variables and then access these after calling join

t = Thread.new { sleep(10);  Thread.current[:output] = "c" }
t.join
t[:output]

There is also a Ruby specific tool, value

t = Thread.new { sleep(10);  "c" }
# This halts execution until the thread is done
t.value
=> "c"

Resources