Are rails controllers multithreaded? Thread.exclusive in controllers

后端 未结 3 648
无人及你
无人及你 2020-12-15 12:56

Are Rails controllers multithreaded?

If so, can I protect a certain piece of code (which fires only once every ten minutes) from being run from multiple threads by

3条回答
  •  轮回少年
    2020-12-15 13:02

    Ruby is single threaded. So at anytime, a controller can only handle one request at a time. If there are more than one requests, these requests are queued up. To avoid this, people usually run a small set of Mongrels to get good concurrency. It works like this(straight from Mongrel WIKI FAQ):

    1. A request hits mongrel.
    2. Mongrel makes a thread and parses the HTTP request headers
    3. If the body is small, then it puts the body into a StringIO
    4. If the body is large then it streams the body to a temp file
    5. When the request is "cooked" it call the RailsHandler.
    6. The RailsHandler sees if the file is possibly page cached, if so then it sends the cached page.
    7. Now you're finally ready to process the Rails request. LOCK!
    8. Still locked, Mongrel calls the Rails Dispatcher to handle the request, passing in the headers, and StringIO or Tempfile for body.
    9. When Rails is done, UNLOCK! . Rails has (hopefully) put all of its output into a StringIO.
    10. Mongrel then takes this StringIO output, any output headers, and streams them back to the client super fast.

      Notice that if there is no locking if the page is cached.

提交回复
热议问题