Best way for waiting for callback to finish

前端 未结 3 1698
渐次进展
渐次进展 2021-02-08 03:14

In the code below, main() function is calling request() function which inter call th_request_async() function which mm_th_done_cb().

What will be the best and efficient

3条回答
  •  难免孤独
    2021-02-08 03:42

    If C++11 is available,you can std::future

    #include 
    int main()
    {
        request();
        std::future myFuture = std::async(mm_th_done_cb);
        //wait until mm_th_done_cb has been excuted;
        int result = myFuture.get();
    }
    

    or you can use synchronization mechanism.such as condition_variable,which is cross-platform.

    #include 
    std::mutex mtx;
    std::condition_variable cv;
    int mm_th_done_cb(int error_code, th_result_s* th_result, void* user_data)
    {
        cv.notify_one();
        return 0;
    }
    
    int main()
    {
        request();
        unique_lock lck(mtx);
        cv.wait(lck);
        return 0;
    }
    

提交回复
热议问题