简体   繁体   中英

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.
When the this_thread::sleep_for() function is called, I get exception saying:

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

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 . 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.

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. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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