Bronze Bronze - 1 year ago 58
C++ Question

Inserting a section of asynchronous code into a C++ function

Okay, so I have a strong feeling that this is really easy to accomplish, and indeed something like this is pretty easy to do in other languages. Only that my C++ is not my strongest language, so I can't quite grasp how this should be done.

I have a function that does some startup things, and then part way through it needs to do some I/O and fetch data from another process. Naturally I could do this with callbacks, but I want to avoid doing this:

startupPt1() {
/* stuff */

startupPt2() {
/* rest of stuff */

Really I want to avoid this because there isn't a logical separation between the actions that happen in parts 1 and 2 here, only that there is some I/O that we want to happen asynchronously in between them.

I currently have that I would use callbacks as above, but other than that I don't know what I should do.

Answer Source

OK, just to elaborate on my comments, you may want something like this:



void startup() {
    // part 1
    auto result = std::async([](){
        // IO part
    // part 2 not relying on the result of IO
    // part 2 that uses IO result as result.get()

This will allow OS to schedule your IO work for you. The only time you can guarantee it is finished is after you called results.get().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download