An essay about double-check
时间:2010-03-27 来源:qytan36
An essay about double-check
In some situations, we often use singleton pattern to ensure only one instance of the object would be created in our system. The code is often like this:
class Singleton |
However, if Singleton::getInstance() is accessed by multiple threads simultaneously, maybe one thread is interrupted just after it passes the check statement, then another thread could enter the object production block too, so the object may be created twice or more times. In this case, there would be more than one object instances in our system, which obeys the idea of singleton factory. To keep the object production block as a crucial area, we could introduce a mutex. Like this:
//v2: |
Now it seems safe enough to ensure only one thread could enter the object production block. It's ture. But the performance issue comes out as a pair of mutex lock and realease operations needs to be executed every time Singleton::getInstance() is called. In fact, after the first call, the instance won't be NULL. So the cost is really very expensive. Don't worry, double-check is designed to solve this problem very well.
//v3: |
- 系统休眠文件删除后果 如何删除计算机的休眠文件 2025-04-22
- 站群服务器是什么意思 站群服务器的作用 站群服务器和普通服务器的区别 2025-04-22
- jQuery插件有何作用 jQuery插件的使用方法 2025-04-22
- jQuery插件有哪些种类 简单的jQuery插件实例 2025-04-22
-