我在多线程环境中做的工作很少。所以,我需要知道下面类的 getInstance 函数是否是线程安全的。这是单例类:
//Singleton class
class S {
// intentionally avoided pointer
static S singleObject;
// Private constructor
s ();
s (S &);
s& operator= (const s&);
public:
// return reference of static object
s& getInstance ()
{
return singleObject;
}
/* Normally with static pointer instance, getInstnace look like as
s& getInstace ()
{
// trying to avoid multiple copies of singleObject
lock_mutex ()
if (singleObject == null)
singleObjecct = new S();
unlock_mutex ();
return *singleObject;
}
*/
};
S S::singleObject;
在 getInstance 函数(未注释)中,返回静态对象的引用。它需要线程安全机制吗?
在第二个 getInstance(已注释)中,如果 singleObject 为空,我们将创建对象。所以,它需要一个锁定机制并且需要同步,对吧?