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

C++ Function Completing Before Other Function Finishes

我正在编写一个 C++ 程序以使用 C++ REST SDK 与互联网交互。我有一个主要功能和一个 webCommunication 功能。代码类似于下面:

 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函数完成之前,main函数还在进行中。如果我将 webCommunication 设为字符串的函数类型并具有

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

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

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

我认为您在描述中遗漏了一个关键字。异步。这表明它 returns 在完成之前。如果你需要它是同步的,你应该在调用之后立即获取一个信号量,并在回调代码中放置一个释放。

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

修改了上面 link 的代码片段(为回调添加了锁):

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

注意:在函数调用后获取互斥量以开始网络处理。添加到回调代码以释放互斥量。以这种方式主线程锁定,直到函数实际完成,然后继续 'pause'.

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

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

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

那么调用函数的时候就可以使用".wait()"了。然后它将等待直到函数执行以继续。看起来像这样:

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

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