开发者

A way to share a variable across multiple httpd threads with Rails?

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

    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? Perhaps using Apache/Passenger workers like this?

开发者_如何学编程

Example code would be appreciated.


Exactly this is possible using global variables. Global variables in Rails are those that start with a dollar sign, like $count.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜