1

我有一个简单的 Sinatra 应用程序,它有一个长期运行的路线:

get '/jobs/new' do
  logger.info "jobs/new start. Thread = #{Thread.current.inspect}"
  sleep 10
  logger.info "end new..."
  erb :'jobs/new'
end

get '/jobs' do
  erb :'jobs/index'
end

我在路线之间有并发访问,但不是同一条路线。

一个例子是,当一个客户端调用时/jobs/new(长时间访问),另一个客户端可以jobs并行调用。但是对同一条路线的并行调用不起作用。在这种情况下,网络服务器 Puma 总是使用相同的线程调用路由:

jobs/new started. Thread = #<Thread:0x007f42b128e600 run>
10 seconds later...
jobs/new ended. Thread = #<Thread:0x007f42b128e600 run>
jobs/new started. Thread = #<Thread:0x007f42b128e600 run> <-- new call. Has to wait till first has finished

另一条路线被不同的线程调用。在路线 1 运行时:

jobs/new started. Thread = #<Thread:0x007f42b128e600 run>
2 seconds later...
jobs started. Thread = #<Thread:0x007f541f581a40 run> <--other thread
8 seconds later...
jobs/new ended. Thread = #<Thread:0x007f42b128e600 run>
jobs/new started. Thread = #<Thread:0x007f42b128e600 run>

我尝试在线程模式下使用 Thin 和 Puma 运行应用程序,但行为相同

4

1 回答 1

0

无论你做什么,我都认为这是不对的。

运行此代码:

# config.ru
require 'bundler'
Bundler.require

get '/jobs/new' do
  logger.info "jobs/new start. Thread = #{Thread.current.inspect}"
  sleep 10
  logger.info "end new..."
  "jobs/new"
end

run Sinatra::Application

与美洲狮:

Puma starting in single mode...
* Version 2.7.1, codename: Earl of Sandwich Partition
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://0.0.0.0:9292
Use Ctrl-C to stop
I, [2013-12-12T14:04:48.820907 #9686]  INFO -- : jobs/new start. Thread = #<Thread:0x007fa5667eb7c0 run>
I, [2013-12-12T14:04:50.282718 #9686]  INFO -- : jobs/new start. Thread = #<Thread:0x007fa566731e38 run>
I, [2013-12-12T14:04:58.821509 #9686]  INFO -- : end new...
127.0.0.1 - - [12/Dec/2013 14:04:58] "GET /jobs/new HTTP/1.1" 200 8 10.0132
I, [2013-12-12T14:05:00.283496 #9686]  INFO -- : end new...
127.0.0.1 - - [12/Dec/2013 14:05:00] "GET /jobs/new HTTP/1.1" 200 8 10.0015
^C- Gracefully stopping, waiting for requests to finish
- Goodbye

结果在2个不同的线程!

于 2013-12-12T13:06:51.823 回答