Why does sleep_for call FreeLibrary?

I am shocked to trace this simple code:

#include <thread> void foo() { for (int i = 0; i < 1000000; ++i) { std::this_thread::sleep_for(std::chrono::nanoseconds(1)); } } int main() { std::thread t(foo); t.join(); } 

Guess what? sleep_for calls FreeLibrary every time!

 kernel32.dll!_FreeLibraryStub@4() msvcr120d.dll!Concurrency::details::DeleteAsyncTimerAndUnloadLibrary(_TP_TIMER * timer) Line 707 msvcr120d.dll!Concurrency::details::_Timer::_Stop() Line 111 msvcr120d.dll!Concurrency::details::_Timer::~_Timer() Line 100 msvcr120d.dll!`Concurrency::wait'::`7'::TimerObj::~TimerObj() msvcr120d.dll!Concurrency::wait(unsigned int milliseconds) Line 155 test826.exe!std::this_thread::sleep_until(const xtime * _Abs_time) Line 137 test826.exe!std::this_thread::sleep_for<__int64,std::ratio<1,1000000000> >(const std::chrono::duration<__int64,std::ratio<1,1000000000> > & _Rel_time) Line 162 test826.exe!foo() Line 6 

Why did sleep_for have to call FreeLibrary?

This program will take 2 seconds with the accelerator library and will take> 3 minutes (lose patience) using msvcrt (Release mode). I can’t imagine.

+1
c ++ visual-c ++ msvc12
source share
1 answer

In Visual C ++ 2013, most of the functionality of the C ++ standard concurrency library is at the top of the Concurrency Runtime (ConcRT) . ConcRT is a lead time that provides collaborative scheduling and locking.

Here, Concurrency::wait uses a thread pool timer to wait. It uses LoadLibrary / FreeLibrary to increase the reference count of the module that hosts the ConcRT runtime while the timer waits. This ensures that the module will not be unloaded while waiting.

I am not a ConcRT expert (I don’t even close it), therefore I am not 100% sure what the exact scenario is in which the ConcRT module can be downloaded here. I know that we made similar changes to std::thread and _beginthreadex to get a reference to the module that hosts the thread callback to ensure that the module will not be unloaded while the thread is executing.

In Visual C ++ 2015, the functionality of the C ++ Standard Library concurrency has been changed to sit directly on top of Windows operating system primitives (e.g. CreateThread , Sleep , etc.) instead of ConcRT. This was done to increase productivity, eliminate problems with correctness when mixing the use of C ++ streaming functions using the functionality of the operating system and as part of the more general defRocus ConcRT.

Please note that on Windows, the accuracy of sleep is milliseconds, and sleep with zero milliseconds usually means "continue to do other useful work before returning to me." If you compile your program using Visual C ++ 2015, each call to wait_for in turn call Sleep(0) , which "forces the thread to abandon the rest of its temporary fragment with any other thread that is ready to run."

+4
source share

All Articles