I have some imported C function that looks like `proc doStuff(..., callback: 
proc(pointer) {.cdecl.}, ctx: pointer)`. It does stuff, and on completion calls 
the callback with ctx. I know that the callback will be called from another 
thread. I'd like to wait for completion in a coroutine. Right now I have 
(roughly) the following setup:
    
    
    type Context = object
      lock: Lock
      done: bool
    
    proc callback(ctx: pointer) {.cdecl.} =
      let ctx = cast[ptr Context](ctx)
      withLock(ctx[].lock):
        ctx[].done = true
    
    proc mycoro() {.async.} =
      ...
      var ctx: Context
      initLock(ctx.lock)
      ctx.done = false
      
      doStuff(..., callback, cast[pointer](addr ctx))
      
      while true:
        withLock(ctx.lock):
          if ctx.done:
            break
        await sleepAsync(1)
      
      ...
    
    
    
    Run

Can I achieve the same result without polling, but somehow directly notifying 
the dispatcher from inside the callback?

Reply via email to