0

how can I stop 2nd thread to access same method that is being used by first thread?

Dee
  • 1,887
  • 19
  • 47

2 Answers2

2

One option is to use @synchronized in the method.

- (NSString *)someMethod {
  @synchronized(self) {
      // do some work
  }
}

It allows the method to be called but will synchronize on itself and protect it's work (and more importantly the data it's working on).

bryanmac
  • 38,941
  • 11
  • 91
  • 99
  • It worked. Thank you. I still have a doubt. Once the process is completed by first thread, does the 2nd thread have access to this method automatically? Do all other threads wait until first thread completes it work? – Dee Aug 25 '12 at 12:32
  • Yes, both threads enter the method, one executes the synchronized block of code and when it does the other will continue execution. – bryanmac Aug 25 '12 at 13:20
  • Here's a deeper explanation on what it does: http://stackoverflow.com/questions/1215330/how-does-synchronized-lock-unlock-in-objective-c – bryanmac Aug 25 '12 at 13:21
0

Have a look at NSLock.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSLock_Class/Reference/Reference.html

Just found it when looking for a C# lock statement, it appears to do the same thing..

There is also another SO thread relating to synchronisation:

How does @synchronized lock/unlock in Objective-C?

Community
  • 1
  • 1
WraithNath
  • 17,658
  • 10
  • 55
  • 82