24

免责声明:我是 ac# ASP.NET 开发人员,正在学习“RoR”。抱歉,如果这个问题没有“得到” RoR,任何更正都非常感谢!

什么是多线程

我对 Web 应用程序中的“多线程”能力的理解是双重的:

  1. 每次 web/app 服务器接收到请求时,它都可以为新请求分配一个线程,从而可以同时运行多个请求。
  2. 应用程序运行时 + 语言允许在单个请求中使用多个线程(例如,在 ASP.NET 中通过“异步”方法和关键字)。

这样,IIS7 + ASP.NET 可以做到点 1 和 2。

我对 RoR 感到困惑

我已经阅读了这两篇文章,它们让我感到困惑:

问题一。

我想我理解 RoR 不太适合上面的第 2 点,也就是说,在同一个请求中有多个线程,我说对了吗?

问题二。

为了清楚起见,RoR 应用程序/Web 服务器也可以做右上方的第 1 点(即多个请求可以同时运行)?RoR 并非总是如此吗?

4

3 回答 3

37

问题 1: 如果需要,您可以在一个请求中生成更多 Ruby 线程,尽管这似乎超出了 Rails 的典型用例。它可用于某些长时间运行的 IO 或外部操作。

问题 2: Ruby 并发的限制因素通常是Global Interpreter Lock. Ruby 的这一特性可防止每个进程在任何给定时间执行超过 1 个 Ruby 线程。只要有非 Ruby 代码执行,例如等待磁盘 IO 或 SQL 响应,就会释放锁。您可以通过使用与默认不同的 Ruby 实现来解决这个问题,例如 JRuby,但不是全部。

PhusionPassenger使用基于进程的并发来并发处理一些请求,所以严格来说,它不是“多线程的”,但仍然是并发的。

这个来自 Ruby MidWest 2011 的演讲有一些关于让多线程 Ruby on Rails 运行的好想法。

于 2012-10-08T02:53:23.077 回答
3

Since this is about "from ASP.NET to RoR" there is another small but important detail to remember: In *nix environments it's common to achieve concurrency of a service application through multi-processing rather than multi-threading. This is an architecture that goes way back and is related to the relatively cheap cost of multi-processing on *nix systems using fork and Copy-on-Write. Each process serves one request at a time in a single thread and the main process controls spawning and killing worker child processes. Multiple requests are served concurrently by different child processes.

Modern service applications, for example Apache, have multi-process, multi-threaded, and even combined modes (where the service forks several processes, each running several threads).

In cases where the application was built with portability at mind (examples again: Apache, MySQL, etc) it is customary to run it in multi-process or combined mode on *nix systems, and in multi-threaded mode on Windows servers.

However, admittedly Rails is somewhat lacking on the Windows front. It's not that you can't run it on Windows, it's just that not a lot of effort went into making sure it runs well and smoothly for production use on Windows servers. It's not a common production platform among the RoR community.

As a result, Eventhough Rails itself is thread-safe since version 2.2, there isn't yet a good multi-threaded server for it on Windows servers. And you get the best results by running it on *nix servers using multi-process/single-threaded concurrency model.

于 2014-03-21T12:10:05.010 回答
2

Rails 作为一个框架是线程安全的。所以,答案是肯定的!

您在此处发布的第二个链接列出了许多在多线程方面表现不佳的 Rails 服务器。他后来提到 nginx 是要走的路(它绝对是最受欢迎的,强烈推荐)。但他没有提到是什么让他得出这个结论。Ruby 1.9.3 最近出现了,并且内置了一些以前不存在的新线程优点。

多线程的使用通常取决于用例。就我个人而言,一年前我曾尝试过一次,它确实有效,但我没有在任何生产代码中使用它,因为我没有遇到过使用多线程比将长时间运行的任务推到一个更有意义的用例后台作业。

我很想对此进行更多探索。所以,如果你能描述你想要达到的目标,那么也许我们可以做一个 POC。

于 2012-10-07T15:52:24.013 回答