0

这是一个非常基本的并发问题。

在 Ruby 中,假设存储在局部变量中的任何状态都是线程安全的是否安全?

具体来说,我正在考虑 Rails 应用程序中的请求。如果我要在 User 类上存储状态,我认为这会带来并发问题。但是如果我实例化一个用户(例如,在请求期间的 Devisecurrent_user方法,假设该方法不使用全局作为其自身的状态),并且我从不将该用户分配给全局变量或常量,我应该是能够在不担心线程安全的情况下修改该实例的状态,对吗?

4

1 回答 1

1

Basically, you are right, inside a single request you can safely use any local variables unless you are spawning any threads yourself.

Also if you use server like Unicorn that uses workers (separate process) for processing requests you are "threadsafe" as each process lives in its own memory space and only one request is being processed at a time.

Problems may occur if you have a threaded server like Puma that can process multiple requests in parallel inside a single Ruby process. This is where race conditions may start and if you have a code like:

class User
  delf.self.current_user
    @@current_user
  end
end

User.current_user.destroy

The @@current_user variable may get changed by parallel process and you can accidentally destroy wrong user.

于 2013-08-23T13:35:56.847 回答