Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby threads order of output?

I'm reading about Ruby Threads (I've never used Ruby before), and I'm surprised about the following code:

t1 = Thread.new { print "w"; Thread.pass; print "a"}
t2 = Thread.new { print "e"; Thread.pass; print "l"}
t1.join
t2.join

The book said that always will show "weal" and I don't understand why, because if they are real threads (as in other languages), it is not ensured that "w" will print before "e".

Thank you for your answers!

like image 803
pianista Avatar asked Feb 12 '23 20:02

pianista


1 Answers

Change the book or read it with care. You are of course right, the only guarantee is that a will show after w etc.

I have just tested your code and here are results after 10 runs:

weal
weal
ewal
wela
wael
wael
wela
ewla
ewla
weal
like image 72
BroiSatse Avatar answered Feb 15 '23 10:02

BroiSatse