Note that there are some explanatory texts on larger screens.

plurals
  1. POChild process and a mutex in Ruby
    primarykey
    data
    text
    <p>I'm creating a script that plays music using <code>mplayer</code>. The way I'm trying to make it work is to allow multiple threads (via HTTP requests) can play a song. However, I don't want multiple songs playing at once, and I don't want a queue. I just want to play the most recent request. I'm having issues, though, with my mutex. It doesn't always return locked when I expect it to. </p> <pre><code>Class Handler def initialize @read_io, @write_io = IO.pipe @child = nil @mutex = Mutex.new end def play_song_with_id(id) if @mutex.locked? then # this doesn't always return as expected stop_mplayer # this is how I interupt the child @mutex.unlock end if @mutex.lock then @child = fork do STDIN.reopen(@read_io) `mplayer -really-quiet "#{id}"` exit end Process.detatch(@child) end end def stop_mplayer() @write_io.write "q" # mplayer takes input 'q' to quit end end </code></pre> <p>And just to give the full picture, here's how I'm routing the requests. A simple WEBrick server:</p> <pre><code>if $0 == __FILE__ then # Create the server server = WEBrick::HTTPServer.new(:Port=&gt;port) ip = IPSocket.getaddress(Socket.gethostname) # Create a handler handler = Handler.new # Define routes server.mount "/handle", Routes::HandleRoute, handler # Handle interuptions trap "INT" do server.shutdown end # Start the server puts "\n====================" puts " * Server running at #{ip} on port #{port}" puts "====================\n\n" server.start end </code></pre> <p>And the route:</p> <pre><code>class HandleRoute &lt; WEBrick::HTTPServlet::AbstractServlet def initialize server, handler @handler = handler end def do_POST(request, response) if(request.body) @handler.play_song_with_id(request.body) end end end </code></pre> <p>TL;DR - Somehow, sometimes two songs will play at once, and I'd like to use <code>@mutex</code> to prevent that. I want to play the most recent request, and stop any playback that is currently happening. I'm wondering the way I'm trying to stop playback is the problem, and not the mutex? If so, what would be a better way to interrupt the child?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload