函数在其他函数完成之前完成

函数在其他函数完成之前完成

本文介绍了C ++函数在其他函数完成之前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C ++程序,以便使用C ++ REST SDK与Internet进行交互。我有一个主要功能和一个webCommunication功能。代码类似于以下内容:

I am coding a C++ program to interact with the internet using the C++ REST SDK. I have a main function and a webCommunication function. The code is similar to below:

 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");
 }

但是,似乎主要功能在webCommunication函数完成之前正在进行中。如果我将webCommunication设为字符串的函数类型,并且

However, it seems that the main function is progressing before the webCommunication function is finished. If I make webCommunication a function type of string and have

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

但这仍然会暂停,然后打印检索到的数据。通常,这很好,希望稍后在代码中引用返回的答案。如果未完成webCommunication,则应用程序将崩溃。我可以使用某种wait_until函数吗?

But that still pauses and then prints the data retrieved. Normally, this would be fine, expect I am referring to the returned answer later on in the code. If the webCommunication isn't completed, the application crashes. Is there some kind of wait_until function I can use?

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

UPDATE: I have tried using a mutex suggested with no success. I also tried starting the function as a thread and then using the .join() with still no success.

推荐答案

如果您声明您的webCommunications()的功能为

If you declare your webCommunications() function as a

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

然后您可以使用 .wait( )。然后它将等待,直到函数执行继续。看起来像这样:

Then you can use ".wait()" when calling the function. It will then wait until the function executes to continue. Looks like this:

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

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

这篇关于C ++函数在其他函数完成之前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:27