我应该与self同步还是与method参数同步? [英] Should I synchronize with self or with the method argument?

查看:95
本文介绍了我应该与self同步还是与method参数同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的方法中,它们是否可以同步(即selfthing)?

In a method like this, which do synchronize (i.e. self or thing)?

- (BOOL)deleteThing:(MSThing *)thing error:(NSError **)error
{
    @synchronized(self)  {
        if (!thing) {
            return YES;
        }

        NSString *fileName = [[self thingDirectory] stringByAppendingPathComponent:thing.cacheInstanceName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
        //...

===或===

- (BOOL)deleteThing:(MSThing *)thing error:(NSError **)error
{
    @synchronized(thing)  {
        if (!thing) {
            return YES;
        }

        NSString *fileName = [[self thingDirectory] stringByAppendingPathComponent:thing.cacheInstanceName];

        if (![[NSFileManager defaultManager] fileExistsAtPath:fileName]) {
        //...

推荐答案

在第一种情况下,

@synchronized(self)  { ... }

代码不会被两个线程同时在同一方法上调用同时执行 实例(self).如果代码访问或修改实例,这可能就是您想要的 以线程不安全的方式.

the code will not be executed simultaneously by two threads calling the method on the same instance (self). This is probably what you want if the code accesses or modifies the instance in a thread-unsafe way.

在第二种情况下,

@synchronized(thing)  { ... }

代码不会被两个线程同时调用的方法同时执行 相同的参数(thing).

the code will not be executed simultaneously by two threads calling the method with the same argument (thing).

这篇关于我应该与self同步还是与method参数同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆