13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

86CHAPTER 4: <strong>Objective</strong>-C Language Features}{}sharedInstance = [[self alloc] init]; //or other initialization}return sharedInstance;Even calling sharedInstance on two different threads will guarantee retrieving the same objectinstance.If an exception is generated during a @synchronized block, the <strong>Objective</strong>-C runtime will catch theexception and release the underlying semaphore before re-throwing the exception. This allowsother threads waiting to execute the protected code to continue their execution.NSConditionalLock is yet another way to synchronize multithreaded programs. This conditionallock maintains an internal state, represented as an integer. Locking an NSConditionalLockrequires a condition; the lock will block until the internal state of the lock is the same as thecondition. Unlocking also accepts a condition; an unlock provides a new state the conditionallock should assume. A pending lock waiting for this condition will stop blocking and enter theircritical section.Conditional locks are important when certain operations must take place in a specific order.The simplest example is a producer-consumer scenario. Consider a producer that places somedata to be processed in a queue and a consumer that dequeues some data to process. Theproducer should not add more data if the consumer hasn’t finished yet and the consumer cannotconsume anything if the queue is empty. Listing 4-15 details a fully synchronized implementationof the producer-consumer pattern.Listing 4-15. Producer-Consumer Patternenum { NO_DATA_IN_QUEUE = 0, HAS_DATA_IN_QUEUE};...NSConditionalLock *conditionalLock;...conditionalLock = [[NSConditionalLock alloc] initWithCondition: NO_DATA_IN_QUEUE];//conditionalLock set up before processing begins...while (YES) //Producer{[conditionalLock lockWhenCondition: NO_DATA_IN_QUEUE];//produce some data and place it in the queue[conditionalLock unlockWithCondition: HAS_DATA_IN_QUEUE];}...while (YES){[conditionalLock lockWhenCondition: HAS_DATA_IN_QUEUE];//remove some data from the queue and consume it[conditionalLock unlockWithCondition: NO_DATA_IN_QUEUE];}Let’s discuss implicit locking mechanisms in <strong>Objective</strong>-C. By default, all properties of an objectdefined with the @property directive are atomic in nature; there is an implicit lock when setting orwww.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!