Jeff Preshing的这篇文章指出双重检查锁定模式(DCLP)在C++ 11中是固定的.用于此模式的经典示例是单例模式,但我碰巧有不同的用例,我仍然缺乏处理"原子<>武器"的经验 - 也许这里有人可以帮助我.
下面的代码是否是Jeff在"使用C++ 11顺序一致的原子"中所描述的正确的DCLP实现?
class Foo {
std::shared_ptr<B> data;
std::mutex mutex;
void detach()
{
if (data.use_count() > 1)
{
std::lock_guard<std::mutex> lock{mutex};
if (data.use_count() > 1)
{
data = std::make_shared<B>(*data);
}
}
}
public:
// public interface
};
Run Code Online (Sandbox Code Playgroud) 看完Gor Nishanov对await和coroutines 的采访后,我决定玩一些可恢复的功能N4131.然后我意识到以下代码在我的第二个问题上打印了'false'(使用Visual Studio 2015 RC和在线编译器测试(需要标志:) /await):
#include <future>
#include <iostream>
using namespace std;
using namespace chrono;
struct Foo
{
future<void> coro(thread::id ui_thread_id)
{
cout << "Q: awaiting result in UI thread? " << boolalpha << (this_thread::get_id() == ui_thread_id) << endl;
auto intermediate_result = __await async([] {
this_thread::sleep_for(250ms);
return 42;
});
cout << "Q: received result in UI thread? " << boolalpha << (this_thread::get_id() == ui_thread_id) << endl;
result = intermediate_result; // race …Run Code Online (Sandbox Code Playgroud)