1

I would like to implement an object that queries a database and executes a query asynchronously.

Suppose we have an object A to query uses the object B. A calls executeQuery method of B and starts to do anything else. ExecuteQuery method of B is asynchronous, non-blocking for quini A. When the result of the query is ready I wish it was notified in B to A with a callback so that A can go and read the result only when ready.

What is the best way to implement this mechanism in C ++ 11?

I tried it with std :: async but instead to read the result in std :: future I would like to receive a callback when my std :: future already contains the result thus avoiding my call becomes a blocker.

Thank You

DaxDeveloper
  • 138
  • 1
  • 13

2 Answers2

0

when you have a future you can use .wait() to wait for execution to finish, or you could use boost::mutex to signal other threads when a certain event has happened, and then have some event function act upon it.

I however think that perhaps you need old fashioned callback function setup - just pass a function pointer to your ExecuteQuery function, then have it call it

serup
  • 3,676
  • 2
  • 30
  • 34
0

You could pass a pointer to function and execute it.

Or use std::future with std::async

You should use wait_for function instead of wait. And check if the result is ready.

You can also set atomic bool value on end of async function. And check this bool value in main thread.

https://en.cppreference.com/w/cpp/thread/future/wait_for