【发布时间】:2015-10-30 11:07:44
【问题描述】:
不久前,我为 Windows API 函数编写了一个简单的包装类。我编写了一组单元测试来验证该类产生的结果与对 API 的直接调用匹配。
最近我回过头来添加有关跨不同线程使用包装类的单元测试。我发现::GetLastError 函数存在一些问题。根据MSDN,该函数应保留每个线程的最后一个错误代码:
检索调用线程的最后一个错误代码值。最后一个错误代码是在每个线程的基础上维护的。多个线程不会覆盖彼此的最后一个错误代码。
我发现在某些情况下,最后一个错误代码实际上变为零。我已经设法用下面的简单程序在单元测试之外复制了这个问题:
#include "stdafx.h"
#include <condition_variable>
#include <mutex>
#include <thread>
#include <Windows.h>
int main(int argc, char* argv[])
{
::DWORD setError1 = 123;
::DWORD setError2 = 456;
// scenario 1 - show that main thread not polluted by sub-thread
const auto act1 = [](::DWORD errorNo)
{
::SetLastError(errorNo);
const auto a = ::GetLastError(); // a = 123
};
::SetLastError(setError2);
const auto b = ::GetLastError(); // b = 456
const auto c = ::GetLastError(); // c = 456
std::thread sub1(act1, setError1);
sub1.join();
const auto d = ::GetLastError(); // d = 0 - WHY???
// scenario 2 - show that sub thread not polluted by main thread
std::condition_variable conditional;
std::mutex mutex;
bool flag = false;
::DWORD e;
const auto act2 = [&mutex, &flag, &e, &conditional](::DWORD errorNo)
{
std::unique_lock<std::mutex> lock(mutex);
::SetLastError(errorNo);
conditional.wait(lock, [&flag] { return flag; });
e = ::GetLastError(); // e = 456 in Windows 8.1, 0 in Windows 10.0.10240.0 - WHY???
};
std::thread sub2(act2, setError2);
{
std::lock_guard<std::mutex> guard(mutex);
::SetLastError(setError1);
flag = true;
}
conditional.notify_all();
sub2.join();
const auto f = ::GetLastError(); // f = 123;
return 0;
}
我遇到的问题是d 和e:
d - 我发现 主线程 的最后一个错误代码在使用子线程时重置为零。
e - 使用 Windows 10 SDK 时,我发现 子线程 在等待
std::condition_variable时看到最后一个错误重置为零。使用 Windows 8.1 SDK 时不会重置。
有人可以帮助解释我看到的结果吗?这是 Windows API 中的错误,还是微软 C++ 实现中的错误?还是我自己的代码中的错误?
【问题讨论】:
标签: c++ multithreading winapi visual-c++ visual-studio-2015