C++顺序嵌套回调函数
当需要有顺序的到多个较慢的设备中读取数据时,一般需要启动一个线程,将回调函数传入线程中,设备中读到数据后,通过传入的回调函数进行操作
#include <iostream>
#include <functional>
#include <thread>
#include <chrono>
class IntReader {
public:
void BeginRead(const std::function<void(int)>& callback)
{
std::thread t([callback]() {
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
int value = 1;
callback(value);
});
t.detach();
}
};
void Print_My()
{
IntReader mm;
int total = 0;
mm.BeginRead([&total](int result1) {
total += result1;
IntReader mm2;
mm2.BeginRead(
[&total](int result2)
{
total += result2;
IntReader mm3;
mm3.BeginRead(
[&total](int result3) {
total += result3;
std::cout << total << std::endl;
}
);
}
);
});
}
int main()
{
Print_My();
std::cout << "Hello World!\n";
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}