0

I am really fond of @synchronized-construct instead of using NSLocks, when I want that a data structure is only read or written by one thread at a time. However, when I want to change the whole object we are @synchronizing on, I am not sure if @synchronized is suitable. What I want to know, is whether these work the same way:

// version 1:

// segment 1:
@synchronized(self.obj) {
    self.obj = obj2;
}
// segment 2:
@synchronized(self.obj) {
    // some other stuff
}

// version 2:
// segment 1:
[objLock lock];
self.obj = obj2;
[objLock unlock];
// segment 2:
[objLock lock];
// some other stuff
[objLock unlock];
mbord
  • 63
  • 1
  • 3
  • possible duplicate of [Changing the locking object insde @synchronized section](http://stackoverflow.com/questions/1215765/changing-the-locking-object-insde-synchronized-section) – kennytm Feb 15 '12 at 11:02

2 Answers2

1

Instead you can set a property without nonatomic. The absence of nonatomic means, it is atomic.

Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment—that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently.

For more info, see Apple documentation

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
0

A NSLock and a @synchronized call are basically the same thing, and are pretty much interchangeable. There are a few minor differences, which you probably don't need to care about for such a simple implementation - but do read up on them, because it's sort of interesting!

There's a good SO answer here that compares the two: How does @synchronized lock/unlock in Objective-C?

Community
  • 1
  • 1
lxt
  • 31,146
  • 5
  • 78
  • 83