简体   繁体   English

我在C ++ 11线程中遇到线程睡眠错误

[英]i get thread sleep error in C++11 threading

I created a thread using C++11 thread class and I want the thread to sleep in a loop. 我使用C ++ 11 thread类创建了一个线程,并且希望该线程在循环中休眠。
When the this_thread::sleep_for() function is called, I get exception saying: 调用this_thread::sleep_for()函数时,出现异常提示:

Run-Time Check Failure #2 - Stack around the variable '_Now' was corrupted. 运行时检查失败#2-变量'_Now'周围的堆栈已损坏。

My code is below: 我的代码如下:

std::chrono::milliseconds duration( 5000 );
while (m_connected)
{
    this->CheckConnection();
    std::this_thread::sleep_for(duration);
}

I presume _Now is a local variable somewhere deep in implementation of sleep_for . 我认为_Now是在sleep_for实现的深处的局部变量。 If it gets corrupt, either there is bug in that function (unlikely) or some other part of your application is writing to dangling pointers (much more likely). 如果损坏,则可能是该函数存在错误(不太可能),或者应用程序的其他部分正在写入悬空指针(很有可能)。

The most likely cause is that you, some time before calling the sleep_for , give out pointer to local variable that stays around and is written to by other thread while this thread sleeps. 最可能的原因是,在调用sleep_for之前的某个时间,您给出了指向本地变量的指针,该指针保留在该本地变量中,并在该线程睡眠时被其他线程写入。

If you were on Linux, I'd recommend you to try valgrind (though I am not certain it can catch invalid access to stack), but on Windows I don't know about any tool for debugging this kind of problems. 如果您使用的是Linux,我建议您尝试使用valgrind (尽管我不确定它可以捕获对堆栈的无效访问),但是在Windows上,我不知道有任何工具可以调试此类问题。 You can do careful review and you can try disabling various parts of functionality to see when the problem goes away to narrow down where it might be. 您可以进行仔​​细的检查,并可以尝试禁用功能的各个部分,以查看问题何时消失,以缩小可能的范围。

I also used to use duma library with some success, but it can only catch invalid access to heap, not stack. 我还曾经使用duma库取得了一些成功,但是它只能捕获对堆的无效访问,而不能捕获堆栈。

Note: Both clang and gcc are further in implementing C++11 than MSVC++, so if you don't use much Windows-specific stuff, it might be easy to port and try valgrind on it. 注意:clang和gcc都比MSVC ++更实现C ++ 11,因此,如果您不使用太多Windows特定的东西,则可能很容易移植并尝试使用valgrind。 Gcc and especially clang are also known for giving much better static diagnostics than MSVC++, so if you compile it with gcc or clagn, you may get some warning that will point you to the problem. Gcc(尤其是clang)还提供比MSVC ++更好的静态诊断程序,因此,如果使用gcc或clagn进行编译,可能会得到一些警告,指出您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM