C++ boost::thread 运算符()() 问题
这是我第一次尝试使用 boost::threads,我有一个愚蠢的问题。 我调用 boost:thread 来使用我的模板类函数之一。但是,在阅读本教程之后它说要构造一个operator()()
,我就是这样做的。 下面的代码能正常工作吗?
template <class S>
class SarsaL : public Task<S,Policy>, protected Method
{
protected:
...
void updateEpsilons(S* avoid);
void step();
...
public:
...
void operator()();
...
};
template <class S>
void SarsaL<S>::operator()()
{
updateEpsilons();
}
template <class S>
void SarsaL<S>::step()
{
S* now_state = Task<S,Policy>::checkIfAdd();
...
...
boost::thread workerThread(&SarsaL<S>::updateEpsilons, this, now_state);
...
...
workerThread.join();
}
我问的原因是因为我在不带参数的运算符中调用 updateEpsilons()
,但在创建线程时我发送了参数 now_state
。这会起作用吗?还是不需要争论?代码编译并执行没有错误,我只是感到困惑。
This is my first attempt to use boost::threads and I have a silly question.
I call a boost:thread to use one of my template class functions. However after reading this tutorial it says to construct an operator()()
which I did.
Will the code below work properly ?
template <class S>
class SarsaL : public Task<S,Policy>, protected Method
{
protected:
...
void updateEpsilons(S* avoid);
void step();
...
public:
...
void operator()();
...
};
template <class S>
void SarsaL<S>::operator()()
{
updateEpsilons();
}
template <class S>
void SarsaL<S>::step()
{
S* now_state = Task<S,Policy>::checkIfAdd();
...
...
boost::thread workerThread(&SarsaL<S>::updateEpsilons, this, now_state);
...
...
workerThread.join();
}
The reason I am asking is because I am calling updateEpsilons()
within the operator without a parameter, yet when creating the thread I send the parameter now_state
. Will this work or take no argument ? Code compiles and executes without error, I am just puzzled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在要执行的对象上提供了一个方法(在本例中为
updateEpsilons
),则不必使用operator()()
。显然这个operator()()
是不正确的,因为它没有使用参数调用适当的updateEpsilons
方法。请注意,在本教程中,创建的新线程仅提供类的实例,而不提供任何方法。在这种情况下,该类必须实现
operator()()
,这就是线程代码所调用的。You don't have to use the
operator()()
if you provide a method on the object to be executed (in this caseupdateEpsilons
). Obviously thisoperator()()
is not correct because it does not call the appropriateupdateEpsilons
method with a parameter.Note that in the tutorial, the new thread is created giving just an instance of a class, and no method. In this case, the class has to implement the
operator()()
, which is what will be called for the code of the thread.