Eu estou codificando um programa C ++ para interagir com a Internet usando o C ++ REST SDK. Eu tenho uma function principal e uma function webCommunication. O código é semelhante ao abaixo:
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"); }
No entanto, parece que a function principal está progredindo antes que a function webCommunication seja concluída. Se eu fizer webCommunication um tipo de function de string e ter
cout << webCommunication(ans1, ans2) << endl;
Mas isso ainda faz uma pausa e depois imprime os dados recuperados. Normalmente, isso seria bom, espere que eu esteja me referindo à resposta retornada mais tarde no código. Se a webcommunication não for concluída, o aplicativo falha. Existe algum tipo de function wait_until que eu possa usar?
ATUALIZAÇÃO: Eu tentei usar um mutex sugerido sem sucesso. Eu também tentei iniciar a function como um segmento e, em seguida, usando o .join () com ainda nenhum sucesso.
Se você declarar sua function webCommunications () como um
pplx::task webCommunications() { }
Então você pode usar “.wait ()” ao chamar a function. Em seguida, ele aguardará até que a function seja executada para continuar. Se parece com isso:
pplx::task webCommunications() { } int main() { webCommunications().wait(); //Do other stuff }
Eu acho que você está perdendo uma palavra-chave nas descrições. ASSÍNCRONO. Isso indica que ele retorna antes de terminar. Se você precisar que ele seja síncrono, você deve colocar um semáforo imediatamente após a chamada e colocar uma liberação no código de retorno de chamada.
https://msdn.microsoft.com/pt-br/library/jj950081.aspx
Snippet de código modificado do link acima (bloqueio adicionado ao retorno de chamada):
// Creates an HTTP request and prints the length of the response stream. pplx::task 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. */ }
Nota: Adquira o mutex após a chamada de function para iniciar o processamento da web. Adicione ao código de retorno de chamada para liberar o mutex. Dessa maneira, o thread principal é bloqueado até que a function realmente seja concluída e continue a "pausar".
int main() { HttpStreamingAsync(); // Acquire lock to wait for complete mutex.lock(); system("PAUSE"); }