On 9 Mar 2011, at 17:47, Chad Johnson <[email protected]> wrote:

> Let's say I have the following threading in my Rails web application:
> 
>    class MyController
>      def my_action
>        count = 0
>        arr = []
> 
>        10.times do |i|
>          arr[i] = Thread.new {
>            sleep(rand(0)/10.0)
>            Thread.current["mycount"] = count
>            count += 1
>          }
>        end

This looks thread dangerous to me - i don't think += is atomic. 
> 
>        arr.each {|t| t.join; print t["mycount"], ", " }
>        puts "count = #{count}"
>      end
>    end
> 
> As you can see, the 'count' variable is shared across all threads.
> 
> **Now,** what I want to do is **share 'count'** across multiple httpd
> requests and **allow my_action in MyController to have access to that
> variable**. For instance, maybe whatever spawns the ruby process to
> serve httpd process could hold the variable count in its scope, and then
> the ruby processes spawned for httpd processes could then access that
> variable.
> 
> Using memcached, a database, and session variables is out of the
> question. Ultimately 'count' will actually be a resource object...an FTP
> connection.
> 
> Is this possible?

I wouldn't go down this road if I were you. For starters presumably the objects 
in question will be modified by those workers, you'll need to synchronise 
access to them etc. You might also be painting yourself into a corner for the 
day you need to scale beyond 1 server. 

Personally, if I had to do this, I'd these objects in a separate long-lived 
process (or processes) and have your controller actions talk to these processes 
(exactly how depends on what you'll be doing, you might consider drb, message 
queues etc)

Fred

> Perhaps using Apache/Passenger workers like at
> http://stackoverflow.com/questions/4471680/a-way-to-access-common-ftp-connection-resource-pool-in-ruby-across-ajax-calls/4471758#4471758?
> 
> Example code would be appreciated.
> 
> -- 
> Posted via http://www.ruby-forum.com/.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Talk" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to 
> [email protected].
> For more options, visit this group at 
> http://groups.google.com/group/rubyonrails-talk?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to