Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Last active August 9, 2019 11:39
Show Gist options
  • Save keithrbennett/6694730 to your computer and use it in GitHub Desktop.
Save keithrbennett/6694730 to your computer and use it in GitHub Desktop.
Getting Sinatra to run alongside other threads in an app.
require 'socket'
require 'sinatra/base'
require 'pry'
puts "Ruby runtime parsing SinatraServer in main thread: #{Thread.current}"
sinatra_thread = Thread.new do
class SinatraServer < Sinatra::Application
puts "Sinatra running in thread: #{Thread.current}"
class << self
attr_reader :sinatra_thread
end
get '/hi' do
"Hello World!"
end
get '/exit' do
exit!(0)
end
run!
end
end
# Test this with the following client code:
# require 'socket'
# s = UDPSocket.new
# s.send("hello", 0, 'localhost', 1234)
class UdpServer
def initialize
@socket = UDPSocket.new
@socket.bind(nil, 1234)
end
def serve
loop do
puts "Waiting for UDP message..."
text, sender = @socket.recvfrom(16)
puts "Got message: #{text}"
end
end
end
udp_thread = Thread.new { UdpServer.new.serve }
puts "created threads..."
# It never gets past here, but that makes sense, because
# neither loop terminates.
threads = [sinatra_thread, udp_thread]
threads.each { |thread| thread.join }
puts "threads joined"
Copy link

ghost commented Jul 22, 2019

Does it still work?

Copy link

ghost commented Jul 22, 2019

Sinatra didn't work for me, made it work with a pure ruby "server" for now.

https://github.com/icetiger-tec/eezee-cd7e7d338253f303aeb0b80059ce5905/blob/master/eezee.rb#L1063

@a0s
Copy link

a0s commented Aug 9, 2019

Sinatra in a thread is still working unless you are using (as I suppose) @socket.recvfrom that block everything in each threads (because GIL).
I've got the same (bad) behavior when tries @redis.brpoplpush.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment