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

后端 未结 7 568
别跟我提以往
别跟我提以往 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 12:00

    There are two bits to doing this.

    Firstly, packing up the function call so that it can be executed later.

    Secondly, scheduling it.

    It is the scheduling which depends on other aspects of the implementation. If you know "when this task is done", then that's all you need - to go back and retrieve the "function call" and call it. So I am not sure this is necessarily a big problem.

    The first part is then really about function objects, or even function pointers. The latter are the traditional callback mechanism from C.

    For a FO, you might have:

    class Callback
    {
    public:
      virtual void callMe() = 0;
    };
    

    You derive from this and implement that as you see fit for your specific problem. The asyncronous event queue is then nothing more than a list<> of callbacks:

    std::list asyncQ; // Or shared_ptr or whatever.
    

提交回复
热议问题