Forum: Ruby simple threading

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Christoph Jasinski (Guest)
on 2009-06-09 13:07
(Received via mailing list)
Hi all,
I wanted to write a program that request stock quotes say every second.
So I
started to write a thread like this:

  require 'rubygems'
  require 'yahoofinance'

  thread=Thread.new do
    YahooFinance::get_historical_quotes_days( 'goog', 10 ) do |row|
      puts "YHOO,#{row.join(',')}"
    end
  end

When I run this I don't get any results. Which is really weird. Got all
the
gems and so on.
But when I do the same code run in IRB it works! without any surprises.
I
don't get it. Really.

Thanks for any help.

Chris
4407f136a22e8f1e04bbee9f4ca39776?d=identicon&s=25 Vikhyat K. (celebrus)
on 2009-06-09 13:24
(Received via mailing list)
On Tue, Jun 9, 2009 at 4:36 PM, Christoph
Jasinski<christoph.jasinski@googlemail.com> wrote:
>    end
>
Not sure, but adding 'thread.join' to the end might help.
Christoph Jasinski (Guest)
on 2009-06-09 14:29
(Received via mailing list)
Thanks,
it works; I don't know why, but it works

Cheers,

Chris
58aa8536f985277ebef53fa931863a3e?d=identicon&s=25 James G. (bbazzarrakk)
on 2009-06-09 15:21
(Received via mailing list)
On Jun 9, 2009, at 7:28 AM, Christoph Jasinski wrote:

> Thanks,
> it works; I don't know why, but it works

I know why it work.  :)  Let me explain:

1.  Your code splits into two threads (the main Thread Ruby started
your program in and the one you created to talk to YahooFinance in)
2.  After you have the two Threads, they both begin working (trading
off time)
3.  Your YahooFinance Thread probably starts talking over the network
4.  However, your main Thread runs off the end of your file and when
that happens, Ruby exits (killing the unfinished YahooFinance Thread)

Thus, Vikhyat had you add a line that asked the main Thread to join()
or wait on the YahooFinance Thread to finish.  That call won't return
until the second Thread ends, so Ruby will wait to exit.

Of course, that means the second Thread doesn't really do anything for
us in this case.  But if you are launching a bunch of them or
continuing to work in the main Thread, there will be benefits.

Hope that helps.

James Edward Gray II
This topic is locked and can not be replied to.