How do I make a function asynchronous in C++?

后端 未结 7 556
别跟我提以往
别跟我提以往 2021-02-02 11:21

I want to call a function which will be asynchronous (I will give a callback when this task is done).

I want to do this in single thread.

7条回答
  •  盖世英雄少女心
    2021-02-02 11:55

    I'm not sure I understand what you want, but if it's how to make use of a callback: It works by defining a function pointer, like this (untested):

    // Define callback signature.
    typedef void (*DoneCallback) (int reason, char *explanation);
    
    // A method that takes a callback as argument.
    void doSomeWorkWithCallback(DoneCallback done)
    {
        ...
        if (done) {
           done(1, "Finished");
        }   
    }
    
    //////
    
    // A callback
    void myCallback(int reason, char *explanation)
    {
        printf("Callback called with reason %d: %s", reason, explanation);
    }
    
    /////
    
    // Put them together
    doSomeWortkWithCallback(myCallback);
    

提交回复
热议问题