运行 Sinatra 服务器和子进程异步

Running Sinatra server and subprocess asynchronously

我正在尝试 运行 一个处理航班跟踪数据并主动将其转换为 JSON 字符串(连续循环过程)的进程以及一个响应 GET 请求的 Sinatra 服务器 JSON 字符串。我正在尝试使用线程来处理这个问题,但没有成功。我如何 运行 这两个进程并排?以下是一些更具体的内容:

我有一个 class Aircraft,其中包含一个名为 Aircraft::AllAircraft 对象数组。我有一个方法可以不断更新这个数组,我想 运行 与 Sinatra 服务器一起使用 JSON 格式的飞机列表响应 GET 请求。

代码如下:

# starting the data stream from external process
IO.popen("./dump1090") do |data|
    block = ""
    # created sinatra server thread
    t1 = Thread.new do
        set :port, 8080
        set :environment, :production

        get '/aircrafts' do
            return_message = {}
            if !Aircraft::All.first.nil?
                return_message[:status] == 'success'
                return_message[:aircrafts] = message_maker
            else
                return_message[:status] = 'sorry - something went wrong'
                return_message[:aircrafts] = [] 
            end
            return_message.to_json
        end
    end
    # parsing the data in main thread -- the process 
    # I want to run alongside the server (parse_block updates Aircraft::All)
    while line = data.gets
        if line.to_s.split('').first == '*'
          parse_block(block)
          puts block
          Aircraft::All.reject { |aircraft| Time.now.to_f - aircraft.contact_time > 30 }
          block = ""  
        end
        block += line.to_s
  end
end

这里主线程是Sinatra应用,附加线程加载数据,这对我来说比较常见。

class Aircraft
  @aircrafts = {}

  def self.all
    @aircrafts
  end
end

Thread.new do
  no = 1
  while true
    Aircraft.all[no] = 'Boing'
    no += 1
    sleep(3)
  end
end

get '/aircrafts' do
  Aircraft.all.to_json
end