Last active
August 9, 2019 11:39
-
-
Save keithrbennett/6694730 to your computer and use it in GitHub Desktop.
Getting Sinatra to run alongside other threads in an app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sinatra didn't work for me, made it work with a pure ruby "server" for now.
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
Does it still work?