Search code examples
rubymultithreadingirbpry

How to prevent irb or pry from starting thread automatically


When I create a new thread in pry or irb, it is immediately started.

[1] pry(main)> th = Thread.new {puts "hi"}
hi
=> #<Thread:0x00007ff09b8e8c10@(pry):1 dead>
[2] pry(main)> th.join
=> #<Thread:0x00007ff09b8e8c10@(pry):1 dead>

...

irb(main):001:0> th = Thread.new {puts 'hi'}
=> #<Thread:0x00007fe2cc91e860@(irb):1 run>
hi
irb(main):002:0> th.join
=> #<Thread:0x00007fe2cc91e860@(irb):1 dead>

Is there any way to prevent this? Not sure how this behavior could be useful; I'd like it to behave like it would if I ran it in a file.


Solution

  • When you run it in a file, they DO start automatically.

    You can immediately pause a thread by issuing a Stop in the beginning of the block.

    th = Thread.new { Thread.stop; puts 'hi' }
    # not running yet
    th.run
    # now will print 'hi'
    th.join