使用哪种同步方法来确保单例仍然是单例?
+(Foo*)sharedInstance
{
@synchronized(self)
{
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
}
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
还是使用互斥?
#import <pthread.h>
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
+(Foo*)sharedInstance
{
pthread_mutex_lock(&_mutex);
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
pthread_mutex_unlock(&_mutex);
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
嗯..对此有何评论?
singleton multithreading memory-management objective-c thread-safety
我是C的新手,我正在查看一些代码来了解哈希.
我遇到了一个包含以下代码行的文件:
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
// ---------------------------------------------------------------------------
int64_t timing(bool start)
{
static struct timeval startw, endw; // What is this?
int64_t usecs = 0;
if(start) {
gettimeofday(&startw, NULL);
}
else {
gettimeofday(&endw, NULL);
usecs =
(endw.tv_sec - startw.tv_sec)*1000000 +
(endw.tv_usec - startw.tv_usec);
}
return usecs;
}
Run Code Online (Sandbox Code Playgroud)
我之前从未遇到过以这种方式定义的静态结构.通常,struct前面是struct的定义/声明.但是,这似乎表明将存在类型为timeval,startw,endw的静态struct变量.
我试图阅读它的作用,但还没有找到足够好的解释.有帮助吗?