C++函数在其他函数完成之前完成
C++ Function Completing Before Other Function Finishes
我正在编写一个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");
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 保留对其他类的成员函数的引用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 如何在其他文件中使用函数
- C++变量名(可以将 main 声明为变量,但对于其他函数名称则不然)
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 为什么 memcpy() 和其他类似的函数使用汇编?
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 泛型枚举和其他类型的重载模板函数
- error dllimport 函数的定义不允许在一个特定的联合中,而其他类、结构和联合将按预期导出
- 将基类的成员函数重载到其他派生类C++
- 如何在其他类中使用参数化构造函数制作类的对象?
- 为什么 ADL 的运算符函数行为与其他函数不同?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 在C++单元测试上下文中,抽象基类是否应将其他抽象基类作为函数参数
- 如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 通过向构造函数其他对象引用页面来创建对象