2014-12-26 37 views
6

在下面的代码中,main()函数调用request()函数,它调用了函数mm_th_done_cb()的th_request_async()函数。等待回调完成的最佳方式

只有在执行了mm_th_done_cb()之后,什么才是在main中继续进行的最佳和有效的方式。

虚设码

int mm_th_done_cb(int error_code, th_result_s* th_result, void* user_data) 
{ 
    return 0; 
} 

void request() 
{ 
    th_request_s MyItemInfo; 
    strncpy(MyItemInfo.origin_path, szUrl, 1024+1); 
    MyItemInfo.orientation = 0; 
    MyItemInfo.func = mm_th_done_cb; 
    MyItemInfo.used_cache = 1; 
    th_request_async(MyItemInfo); 
} 


int main() 
{ 
    request(); 
    // Here I need to do something only after mm_th_done_cb() has been excuted. 
} 
+0

将呼叫,使其成为自由语句之前NULL。 –

回答

4

如果C++ 11是可用的,你可以标准::未来

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

,或者您可以使用同步mechanism.such为condition_variable,它是跨平台。

#include <condition_variable> 
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<std::mutex> lck(mtx); 
    cv.wait(lck); 
    return 0; 
} 
+0

th_request_async();函数调用传递给MyItemInfo.func = mm_th_done_cb的mm_th_done_cb函数;在mm_th_done_cb回调函数中,我检索了我所称的th_request_async所需的值。 – dearvivekkumar

+0

在我的情况下,我必须调用3个类似的函数来获取值,在此之前,我必须等待。我需要以最好的方式处理这种情况的建议。 – dearvivekkumar

+0

Main()正在调用调用请求()请求正在调用th_request_async()这是一个正在调用已注册的回调函数的库函数mm_th_done_cb() – dearvivekkumar

7

您可以使用std::promise

std::promise<int> promise; 

int mm_th_done_cb(int error_code, th_result_s* th_result, void* user_data) 
{ 
    promise.set_value(error_code /*this value will be returned by the future.get()*/); 
    return 0; 
} 

int main() 
{ 
    std::future<int> future = promise.get_future(); 
    request(); 
    int value = future.get(); 
    return 0; 
} 

如果你不需要从回调返回任何值,那么你可以使用一个std::promise<void>std::future<void>对。

吴强的答案都是错的。

1.

#include <future> 
int main() 
{ 
    request(); 

    // WRONG: Here we don't want to call 'mm_th_done_cb' ourselves. 
    std::future<int> myFuture = std::async(mm_th_done_cb); 

    //wait until mm_th_done_cb has been excuted; 
    int result = myFuture.get(); 
} 

2.

#include <condition_variable> 

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(); 

    // WRONG: If the 'request' finishes quickly, then the 'mm_th_done_cb' 
    // callback will be called and will notify the condition variable before 
    // the following lines execute, i.e. before the main thread starts 
    // waiting on the condition variable. Thus the 'cv.wait(lck)' will 
    // never return. 

    unique_lock<std::mutex> lck(mtx); 
    cv.wait(lck); 
    return 0; 
}