1
a = Thread.new { 5.times { |i| p i; sleep 0.1 } } a.join p 'a' b = Thread.new { 5.times { |k| p k; sleep 0.1 } } b.join p 'b' 

This will print out 01234a01234b. What I want it to print out is: 001122334a4b.
p 'b' and p 'a' must both be outside of threads. They must execute after corresponding thread is finished. a and b threads must execute concurrently.

How can it be done?

4
  • "They must execute after corresponding thread is finished" - just put them at the end of thread bodies then, no? Commented Nov 11, 2014 at 19:20
  • @SergioTulentsev, actually yes, first I decided it's not possible in my case but I looked at it again and see that it is. This would solve one problem. Commented Nov 11, 2014 at 19:52
  • @lakesare if your question has been resolved, please select an answer below as the "accepted answer" (green checkmark). Commented Aug 17, 2015 at 20:38
  • 1
    @HunterStevens, yep, thanks for reminding me. Commented Aug 17, 2015 at 20:42

1 Answer 1

3

Well, if you change when you join, you'll get pretty close.

a = Thread.new { 5.times { |i| p i; sleep 0.1 } } b = Thread.new { 5.times { |k| p k; sleep 0.1 } } a.join b.join p 'a' p 'b' 

But this behavior is not guaranteed. Without some kind of thread synchronization, you'll get whatever the scheduler wants you to get. Do you always want that exact ordering?

Sign up to request clarification or add additional context in comments.

6 Comments

it's important to place a.join after a thread block and b.join after b thread block in my application. and p 'a' must fire exactly when a block is finished, because its value is produced in a thread. actually here is my code if it'll be clearer what I'm trying to achieve: github.com/lakesare/credits/blob/master/credits.rb
If the joins have to occur where they do in your example, I don't believe it's possible to do what you want.
yes, it looks like it, or I should change my architecture completely.
@lakesare it sounds like you don't understand the purpose of join: it blocks the main thread until the joined thread finishes. There is simply no way to have b run concurrently with a if you join a before creating b.
@Max, that's true, I'm very confused about them (in my example they exists only so that errors are produced if something goes wrong in a thread). so joins must follow one after another to execute concurrently?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.