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

C++ Function Completing Before Other Function Finishes

本文关键字:函数 其他 C++      更新时间:2023-10-16

我正在编写一个C++程序,以便使用C++REST SDK与互联网进行交互。我有一个主要功能和一个网络通信功能。代码如下所示:

 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作为字符串的函数类型,并具有

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

但这仍然会暂停,然后打印检索到的数据。通常情况下,这会很好,但我稍后会在代码中引用返回的答案。如果webCommunication没有完成,应用程序就会崩溃。我可以使用某种等待功能吗?

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

如果您将webCommunications()函数声明为

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

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

pplx::task<void> webCommunications()
{
}
int main()
{
webCommunications().wait();
//Do other stuff
}

我认为您在描述中缺少一个关键字。异步。这表示它在完成之前返回。如果您需要它是同步的,那么应该在调用之后立即放入信号量获取,并在回调代码中放入释放。

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.
    */
}

注意:在函数调用后获取互斥,以启动web处理。添加到回调代码中以释放互斥对象。通过这种方式,主线程锁定,直到函数真正完成,然后继续"暂停"。

int main()
{
    HttpStreamingAsync();
    // Acquire lock to wait for complete
    mutex.lock();
    system("PAUSE");
}
相关文章: