A thread key is a symbol or string that associates a value with a thread's built-in storage hash. Indexing the Thread object reads or writes that thread-specific value. section 14.5.4 section 14.5.5
Thread keys support several practical operations:
- Assign values inside a thread with Thread.current[:name] = value, then retrieve them through the thread object with t[:name]. section 14.5.5
- Use keys to list stored names with keys; values remain queryable even after the thread has completed. section 14.5.5
- Use fetch(key, default) for a fallback value, or fetch(key) when a missing key should raise KeyError. section 14.5.5
- Keep thread-specific data separate from another thread's state, avoiding collisions between per-thread values such as regular-expression match variables. section 14.5.4
Per-player state in a threaded game
A networked rock/paper/scissors server stores each worker's player number, connection, and move as :number, :player, and :move thread keys. After both workers join, the main thread fetches their moves and passes them to the RPS comparison logic. section 14.5.5
>> t = Thread.new do
Thread.current[:message] = "Hello"
end
=> #<Thread:0x0000000127213a90 (irb):12 run>
>> t.join
=> #<Thread:0x0000000127213a90 (irb):12 run
p t.keys
puts t[:message]
See a complete set-and-get interaction using Thread.current, join, keys, and direct Thread indexing. section 14.5.5
