Ensure IO computations are run in a specific thread

Viewed 139

I need to make sure that some actions are run on a specific OS thread. I wrote an API where this thread runs a loop listening to a TQueue and executes the given commands. From the API user side, there is an opaque value that is really just a newtype over this queue.

One problem is that what I really need is to embed arbitrary actions (type IO a), but I believe I can't directly exchange messages of that type. So I currently have something like this (pseudo code) :

makeSafe :: RubyInterpreter -> IO a -> IO (Either RubyError a)
makeSafe (RubyInterpreter q) a = do
    mv <- newEmptyTMVarIO
    -- embedded is of type IO (), letting me send this in my queue
    let embedded = handleErrors a >>= atomically . putTMVar mv
    atomically (writeTQueue q (SomeMessage embedded))
    atomically (readTMVar mv)

(for more details, this is for the hruby package)

edit - clarifications :

  • Being able to send actions of type IO a would be nicer, but is not my main objective.
  • My main problem is that you can shoot yourself in the foot with this API, for example if there is a makeSafe call in the IO action that is passed as a parameter, this will hang.
  • My secondary problem is that this solution feels a bit contrived, and I wondered if there was a nicer/safer solution around.
0 Answers
Related