I am new to using callbacks in C++. I found some terms related to callbacks and it is making me confused. I want to know the details about callback and registering a callback in C++. Are they both the same? Are they different? When and how to use each one? I will be grateful if anyone can help me understand these with simple examples.
Thanks in advance.
In terms of real life scenario. We have Alice who wants to receive package from Shop as soon as possible, but does not want to wait in the Shop until the package is ready. But Alice has a friend, Bob, who has lots of time and can wait in the Shop. So Alice comes with Bob to the shop and says, hey prepare a package for me, and give it to Bob when it is ready. In this scenario Shop is external service, Bob is callback, and Alice saying that package shall be given to Bob is registering callback, and Shop giving package to Bob is executing callback.
#include <thread>
#include <iostream>
using namespace std::literals;
void Bob(const char* what)
{
std::cout << "Bob received:" << what << "\n";
}
void Shop(void(callback)(const char*))
{
std::cout << "Shop is very busy with preparing packagae\n";
std::this_thread::sleep_for(200ms);
std::cout << "Package ready, Shop will execute callback\n";
callback("package");
}
void Alice()
{
std::cout << "Alice will register callback at Shop (and start Shop BTW)\n";
std::thread prepare_package(Shop, Bob);
std::cout << "Alice can do something else\n";
std::this_thread::sleep_for(100ms);
std::cout << "Alice still can do something else\n";
prepare_package.join();
}
int main()
{
Alice();
}