TransWikia.com

C++ waiting for response asynchronously, best design?

Stack Overflow Asked on February 11, 2021

I have a program with a main loop which must keep running. Sometimes requests will be made to the network so I defer them to a request making service which spawns another thread. What is the best way to act on the eventual response?

My idea is to set a variable when making the request, protect it by a mutex and have the service thread flip the variable when it is finished, with the response. This means I must continually check the variable in the main loop. Is this the best way?

I’m familiar with async programming in Javascript, but there there is only one thread, so a callback can do all the work safely.

Thank you.

EDIT: I’m using C++ 17.

One Answer

For a lot of traffic I would use a thread to perform the networking, use an "IPC" object containing a mutex, deque and condition-variable.

Use a std::shared_ptr to share the IPC to both main and thread contexts.

When the thread receives the message, it will lock the mutex (use std::lock_guard) and push the message to the deque. Outside the lock, then signal the condition-variable.

The main thread would wait on the condition-variable, when signalled it will then lock the mutex and pop anything from the deque. Note that you use the mutex to protect only the deque.

.

Another approach would be to use a std::async method to receive the message and the main program would wait on it with the get method which will wait until the async method completes.

I'd put the choice largely down to how much networking you are intending to do; if only an occasional "open-send-receive-close" transaction then certainly look at using async.

Answered by Den-Jason on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP