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: |