【发布时间】:2015-08-26 15:23:34
【问题描述】:
追踪这个简单的代码让我很震惊:
#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();
}
你猜怎么着? sleep_for 每次都调用 FreeLibrary!
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
为什么 sleep_for 必须调用 FreeLibrary ?
该程序使用 boost 库需要 2 秒,使用 msvcrt(发布模式)需要 3 分钟以上(失去耐心)。我无法想象。
【问题讨论】:
-
我不明白您如何期望睡眠 1 纳秒 起作用。
-
这是一个非常特定于实现的东西,只有 Visual C++ 标准库开发人员才能知道答案。
-
@JoachimPileborg:幸运的是,其中一些开发人员经常这样做 :)
-
睡眠可以预期释放当前时间片。因此(假设 10ms 时间片)您希望程序休眠 2.7 小时。
-
幸运或不幸... :-) 我们还发布了几乎所有的运行时库源代码,因此单步执行运行时库代码以查看发生了什么通常非常简单。在这种情况下,
Concurrency::wait和_Timer类的 ConcRT 代码有许多有用的 cmets。
标签: c++ visual-c++ msvc12