Skip to content

Working with third parties's modules

Yuki Takei edited this page Oct 11, 2016 · 2 revisions

Process.qwork (uv_queue_work wrapper in Swift)

uv_queue_work() is a convenience function that allows an application to run a task in a separate thread, and have a callback that is triggered when the task is done. A seemingly simple function, what makes uv_queue_work() tempting is that it allows potentially any third-party libraries to be used with the event-loop paradigm. When you use event loops, it is imperative to make sure that no function which runs periodically in the loop thread blocks when performing I/O or is a serious CPU hog, because this means that the loop slows down and events are not being handled at full capacity.

However, a lot of existing code out there features blocking functions (for example a routine which performs I/O under the hood) to be used with threads if you want responsiveness (the classic ‘one thread per client’ server model), and getting them to play with an event loop library generally involves rolling your own system of running the task in a separate thread. libuv just provides a convenient abstraction for this.

Usage

let onThread = { ctx in
    do
        ctx.storage["result"] = try blokingOperation()
    } catch {
        ctx.storage["error"] = error
    }
}

let onFinish = { ctx in
    if let error = ctx.storage["error"] as? Error {
        print(error)
        return
    }

    print(ctx.storage["result"])
}

Process.qwork(onThread: onThread, onFinish: onFinish)
Clone this wiki locally