我已經把一個簡單的C++是應該Timer類週期性地從各種例子對SO如下調用給定函數:C++ 11:調用C++函數定期
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class CallBackTimer
{
public:
CallBackTimer()
:_execute(false)
{}
void start(int interval, std::function<void(void)> func)
{
_execute = true;
std::thread([&]()
{
while (_execute) {
func();
std::this_thread::sleep_for(
std::chrono::milliseconds(interval));
}
}).detach();
}
void stop()
{
_execute = false;
}
private:
bool _execute;
};
現在我希望讓此從一個C++類如followsL
class Processor()
{
void init()
{
timer.start(25, std::bind(&Processor::process, this));
}
void process()
{
std::cout << "Called" << std::endl;
}
};
然而,這要求與該錯誤
terminate called after throwing an instance of 'std::bad_function_call'
what(): bad_function_call
它是否與一個獨立函數'void foo(){}'一起使用? – stefan
你是否真的等待線程在某個點完成?你完全分離它,你確定你的主線程還沒有銷燬相關的'Processor'對象嗎? – KillianDS
@KillianDS這很可能是發生了什麼事情。 Luca,你應該發佈[MCVE](http://stackoverflow.com/help/mcve)。如果你'.join()'線程會發生什麼? – vsoftco