liveBook · Manning

Thread key

As explained in The Well-Grounded Rubyist, Fourth Edition

A thread key is a symbol or string used to associate a value with a thread's built-in key-value storage.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains key types, indexing, listing, defaults, and missing-key errors, then applies them in a threaded server.
Examples
Uses IRB set-and-get snippets, fetch defaults, and a TCPServer-based rock/paper/scissors game.
What it assumes
Assumes Ruby thread objects and basic indexing syntax while demonstrating thread-specific storage from concrete examples.
What you can do after
Apply it via Thread#[] and Thread#fetch to store, retrieve, enumerate, and safely default per-thread state.
How it connects
Connects threads with thread-specific values, regular-expression match variables, and networked games.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.