#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <thread>
#include <atlstr.h>
#include <atlconv.h>
#include <cassert>
#include <codecvt>
std::wstring utf82ws(const char* str)
{
auto& err = get_error_string();
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv(err.err, err.werr);
return conv.from_bytes(str);
}
//assert(wcscmp(CA2W(strUtf8.c_str(), CP_UTF8).m_psz, strWs.c_str()) == 0);
void f()
{
std::string strUtf8 = "hello,world";
std::wstring strWs = L"hello,world";
int i = 0;
while (1) {
assert(utf82ws(strUtf8.c_str()) == strWs);
if (++i == 1000) {
i = 0;
}
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
return 1;
}
cpu 运行结果如下:
预期两个while 死循环,cpu 占用应该是25%,wpa 分析一下:
按照等待时间排序,排查一下是否有锁操作
左边是cpu 执行的比率,显然,对于那种不干活的,我们不关心,因此,分析10584和25392线程即可:
具体这么设计的原因是啥,不可知。
测试微软的WideCharToMultiByte函数:,ca2w 内部实现就是这个:
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <thread>
#include <atlstr.h>
#include <atlconv.h>
#include <cassert>
#include <codecvt>
std::wstring utf82ws(const char* str)
{
auto& err = get_error_string();
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv(err.err, err.werr);
return conv.from_bytes(str);
}
void f()
{
std::string strUtf8 = "hello,world";
std::wstring strWs = L"hello,world";
int i = 0;
while (1) {
//assert(utf82ws(strUtf8.c_str()) == strWs);
assert(wcscmp(CA2W(strUtf8.c_str(), CP_UTF8).m_psz, strWs.c_str()) == 0);
if (++i == 1000) {
i = 0;
}
}
}
int main() {
std::thread t1(f);
std::thread t2(f);
t1.join();
t2.join();
return 1;
}
看到了我们的理想,25%
这种莫名其妙的锁,简直就是性能杀手,官方文档暂时没有找到介绍这里的锁的东西,暂时不管了,这个函数还是少用