我有一个程序,我不能使用标准std::async
和线程机制。相反,我必须像这样编写程序:
void processor( int argument, std::function<void(int)> callback ) {
int blub = 0;
std::shared_ptr<object> objptr = getObject();
// Function is called later.
// All the internal references are bound here!
auto func = [=, &blub]() {
// !This will fail since blub is accessed by reference!
blub *= 2;
// Since objptr is copied by value it works.
// objptr holds the value of getObject().
objptr->addSomething(blub);
// Finally we need to call another callback to return a value
callback(blub);
};
objptr = getAnotherObject();
// Puts func onto a queue and returns immediately.
// func is executed later.
startProcessing(func);
}
我现在想知道我是否做得对,或者使用 lambdas 作为异步回调的最佳方式是什么。
编辑:在代码注释中添加了预期的行为。有关问题的可能解决方案,请参阅答案/评论blub
。