2016-06-12 76 views
0

我在玩boost :: future .then()功能。我寫了一個以異步方式讀取文件的小型反應堆。有一個函數readFileAsync(int fd),它返回文件數據的未來。當描述符準備就緒並且履行承諾時,該反應器將讀取固定數量的字節。然而,如果可以從文件中獲取更多數據,我仍然決定如何重新啓動未來。做這件事的模式是什麼?是否可以重新啓動boost :: future?

readFileAsync(fd).then([&](auto future) { 
    auto data = future.get(); 
    if (data.block.empty()) { // end of file 
    close(data.fd); 
    } else { 
    readFileAsync(data.fd).then(...); // XXX: how to work that out? 
    } 
}); 

回答

1

而是匿名的lambda,創造正常的經常性功能:

struct continue_reading 
{ 
    template <typename T> 
    void operator()(T future) 
    { 
     auto data = future.get(); 
     if (data.block.empty()) { // end of file 
      close(data.fd); 
     } else { 
      readFileAsync(data.fd).then(continue_reading); 
    } 
}; 

//... 

readFileAsync(fd).then(continue_reading) 
相關問題