C ++堆栈变量已损坏

时间:2017-10-02 13:42:20

标签: c++ multithreading timer

我正在尝试实现一个计时器,它将一个函数指针作为参数,一个时间以毫秒为单位。传递时间后,应在单独的线程中调用该函数。代码如下:

class timer
{
public:
    void schedule(void(*function)(), int time)
    {
        std::thread t = std::thread([&]
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(time));
                function(); 
            });
        t.detach();
    }
};

主要方法如下:

#define LOG(x) std::cout << x << std::endl;


timer t1;
timer t2;
timer t3;
t1.schedule([] {LOG("t1 done")}, 2000);
t2.schedule([] {LOG("t2 done")}, 3000);
t3.schedule([] {LOG("t3 done")}, 4000);
std::this_thread::sleep_for(std::chrono::seconds(20));

例外情况如下:

Run-Time Check Failure #2 - Stack around the variable 't1' was corrupted.

1 个答案:

答案 0 :(得分:2)

这里的问题是你在lambda中通过引用捕获。这意味着您可以在调用lambda的detach之前调用schedule并退出operator()。如果发生这种情况,那么当您尝试使用time时,您正在访问悬空参考。

这里的解决方案是通过价值来捕捉。这意味着你得到一个副本,并且调用operator()时无关紧要,因为lambda不依赖于任何东西。