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

后端 未结 7 569
别跟我提以往
别跟我提以往 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:06

    This can be done portably with modern C++ or even with old C++ and some boost. Both boost and C++11 include sophisticated facilities to obtain asynchronous values from threads, but if all you want is a callback, just launch a thread and call it.

    1998 C++/boost approach:

    #include 
    #include 
    #include 
    void callback(const std::string& data)
    {
        std::cout << "Callback called because: " << data << '\n';
    }
    void task(int time)
    {
        boost::this_thread::sleep(boost::posix_time::seconds(time));
        callback("async task done");
    }
    int main()
    {
        boost::thread bt(task, 1);
        std::cout << "async task launched\n";
        boost::this_thread::sleep(boost::posix_time::seconds(5));
        std::cout << "main done\n";
        bt.join();
    }
    

    2011 C++ approach (using gcc 4.5.2, which needs this #define)

    #define _GLIBCXX_USE_NANOSLEEP
    #include 
    #include 
    #include 
    void callback(const std::string& data)
    {
        std::cout << "Callback called because: " << data << '\n';
    }
    void task(int time)
    {
        std::this_thread::sleep_for(std::chrono::seconds(time));
        callback("async task done");
    }
    int main()
    {
        std::thread bt(task, 1);
        std::cout << "async task launched\n";
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout << "main done\n";
        bt.join();
    }
    

提交回复
热议问题