How to tick when `in_thread`

I’m trying to tick a ring inside a thread, but it’s stuck at 0.

The code below shows the ring ticking for the live_loop, but stuck at 0 for the thread.

live_loop :x do
  in_thread name: :y do
    puts "tick in_thread: #{(ring 0, 1, 2).tick}"
    sleep 1
  puts "tick in live_loop: #{(ring 0, 1, 2).tick}"
  sleep 1

Tested in 3.3.1 and beta 4.0
Is there any way to make this work?

Thanks :slight_smile:

Hey @SuperSpasm,

The reason you are observing this is because the counter that tick increments is not ‘global’.

Every time the live_loop repeats, a thread named y is created, tick returns 0, the thread sleeps for 1, and then the thread completes.

Since tick is ‘thread and live_loop local’, the tick that is used in the thread increments a counter specific (local) to that thread - and thus it only has a chance to be ‘incremented’ once. The next time a new thread is created, the counter that tick operates on is a totally new one. :slightly_smiling_face:

As to how to make a counter in the thread continue to increment between cycles of the containing live_loop, well, there are ways. Looking at your code though, (and without knowing the wider context of your particular goal) my instinct would say that if you want to increment through a list/ring in that thread, (which involves, well, repetition) then having a a series of single short lived threads inside the live_loop perhaps doesn’t suit that well. You could extract the thread out and have it as a separate live_loop instead - that way, it stays around between iterations, and you can tick through its list no problem!

If you do want to keep the thread as-is inside the live_loop, sure - though it might be helpful to understand your goal in a little more detail :slight_smile: