TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Low-Lock Singletons In D

30 点作者 andralex大约 12 年前

4 条评论

WalterBright大约 12 年前
This is an elegant solution to the double checked locking bug <a href="http://en.wikipedia.org/wiki/Double-checked_locking" rel="nofollow">http://en.wikipedia.org/wiki/Double-checked_locking</a>, incurring insignificant overhead.
评论 #5661254 未加载
jamesaguilar大约 12 年前
Or you could use atomic swaps on the initialized bit. That's both cheaper and simpler.<p>psuedocode:<p><pre><code> member atomic32 init member mutex lock member obj ptr membarrier() if (atomic_load(&#38;init)) { return ptr } else { locked_init() atomic_save(&#38;init, 1) membarrier() } </code></pre> Not an expert, use this at your own risk.
评论 #5661394 未加载
评论 #5661401 未加载
评论 #5661322 未加载
brazzy大约 12 年前
Doesn't D have the ability to do stuff on class initialization? Or does it not initialize classes lazily?<p>In Java, this is how a threadsafe Singleton looks like:<p><pre><code> private static MySingleton instance = new MySingleton(); </code></pre> It will be initialized when the class is first used.<p>The whole double-checked locking and TLS thing is IMO a huge pointless smartassery contest in VM lawyering hinging on the eminently false premise that having singletons in a heavily multithreaded environment initialized sooner than they're used is a problem that anyone needs solved.<p>Whereas in reality, 90% of all applications don't need lazy loading, and for 90% of those that do, the above is lazy enough.
评论 #5661669 未加载
评论 #5662346 未加载
vy8vWJlco大约 12 年前
I don't think thread-local variables are necessary.<p>Consider a global flag that gets instantiated and synchronized across threads/cores to a state of 0 such that if it ever gets set to 1, it was after publishing and synchronizing the shared instance via a global pointer. This pointer, and the global flag, will not revert for the rest of the singleton's life (noted in the article) - so there is nothing to synchronize past that - and it is only for the guarding flag's 0 (unallocated) case that there is a question if things are synchronized. That check and potential allocation are what need a standard lock (provided by D's syncronized block), which the example already provides.
评论 #5661404 未加载