2015-04-03 105 views
1

我正在编写一个C++程序,以使用C++ REST SDK与Internet进行交互。我有一个主要功能和一个Web通信功能。该代码类似于以下内容:完成其他函数完成之前的C++函数

void webCommunication(data, url) 
{ 
//Communicate with the internet using the http_client 
//Print output 
} 

int main() 
{ 
//Obtain information from user 
webCommunication(ans1, ans2); 
system("PAUSE"); 
} 

但是,似乎主要功能在web通信功能完成之前正在进行。如果我做webCommunication函数字符串类型,并有

cout << webCommunication(ans1, ans2) << endl; 

但仍然暂停,然后打印检索到的数据。通常情况下,这会很好,希望我在后面的代码中引用返回的答案。如果网络通信未完成,则应用程序崩溃。有什么可以使用的wait_until函数吗?

更新:我尝试使用互斥建议没有成功。我也尝试将该函数作为一个线程启动,然后使用.join()仍然没有成功。

+0

检查REST SDK是否有等待线程完成的函数。 – 2015-04-03 15:38:12

回答

0

如果你宣布你webCommunications()函数作为

pplx::task<void> webCommunications() 
{ 
} 

然后你可以使用 “.wait()” 调用函数时。然后它会等待,直到函数执行继续。看起来像这样:

pplx::task<void> webCommunications() 
{ 
} 

int main() 
{ 
webCommunications().wait(); 
//Do other stuff 
} 
0

我认为你在描述中缺少一个关键字。异步。这表示它在完成前返回。如果你需要它是同步的,你应该在调用之后立即获取一个信号量,并将一个版本放入回调代码中。从上述(加入锁回调)链路

https://msdn.microsoft.com/en-us/library/jj950081.aspx

修改后的代码片断:

// Creates an HTTP request and prints the length of the response stream. 
pplx::task<void> HTTPStreamingAsync() 
{ 
    http_client client(L"http://www.fourthcoffee.com"); 

    // Make the request and asynchronously process the response. 
    return client.request(methods::GET).then([](http_response response) 
    { 
     // Print the status code. 
     std::wostringstream ss; 
     ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl; 
     std::wcout << ss.str(); 

     // TODO: Perform actions here reading from the response stream. 
     auto bodyStream = response.body(); 

     // In this example, we print the length of the response to the  console. 
     ss.str(std::wstring()); 
     ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl; 
     std::wcout << ss.str(); 

     // RELEASE lock/semaphore/etc here. 
     mutex.unlock() 
    }); 

    /* Sample output: 
    Server returned returned status code 200. 
    Content length is 63803 bytes. 
    */ 
} 

注:采集函数调用后互斥启动卷筒纸加工。添加到回调代码以释放互斥锁。以这种方式,主线程锁定,直到函数实际完成,然后继续“暂停”。

int main() 
{ 
    HttpStreamingAsync(); 
    // Acquire lock to wait for complete 
    mutex.lock(); 
    system("PAUSE"); 
} 
+0

我试着创建一个mutex mtx,然后在调用我的httpRequest函数并在httpRequest函数期间解锁后锁定它。但是,它仍然无法工作 - httpRequest函数在完成httpRequest之前正在执行解锁。试图把解锁在不同的位置,并仍然是相同的结果。 – Steven 2015-04-04 14:25:47

+0

也许如果你提供了这个代码,我们可以进一步修复它。在我提供的代码片段中,只有在接收并处理了http_response之后,才会执行互斥锁解锁。也就是说,您应该在互斥体释放之前看到内容长度的输出。您也应该能够在解锁之前进行睡眠来验证这一点,或者使用带断点的调试器来查看事件发生的时间。 – LawfulEvil 2015-04-06 19:08:07

相关问题