我正在寻找如何实现这个场景: 我有函数内部的逻辑代码, 现在我希望能够在单独的线程中执行此功能。 现在我拥有的是这个 .. 的原始实现 我简单地初始化线程,在它的启动/运行方法中我保留了函数逻辑。 我怎样才能让它更通用?所以我可以发送函数(也许是函数指针) 通用线程工厂/池? 在 C++ 中
最佳答案
这是命令模式。通常的解决方案是将逻辑捆绑到一个函数对象中:
class DoSomething {
public:
// Constructor accepts and stores parameters to be used
// by the code itself.
DoSomething(int i, std::string s)
: i_(i), s_(s) { }
void operator()() {
// Do the work here, using i_ and s_
}
private:
int i_;
std::string s_;
};
关于C++ : looking away to implement this scenario,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780285/