Lock and application in Objective-c -13-multithreading

Source: Internet
Author: User
Tags mutex posix

objective-locks and applications in C in multithreaded programming, locks are a very important tool, and objective-C provides several different types of locks, so let's look at how these locks are used. 0. POSIX Mutex Lockmutex Lock is also a mutex, Unix/A set of synchronization mechanisms available on the Linux platform. The mutex provides three functions that can be known from the function name:intPthread_mutex_lock (pthread_mutex_t *mutex);intPthread_mutex_trylock (pthread_mutex_t *mutex);intPthread_mutex_unlock (pthread_mutex_t *mutex), the function Pthread_mutex_trylock and Pthread_mutex_lock are identical, except that the former will return immediately if the lock fails, while the latter will block until the lock is acquired. The use of mutexes is very simple, directly call the above three API can be: pthread_mutex_t mutex;voidmyinitfunction () {Pthread_mutex_init (&mutex, NULL);} voidmylockingfunction () {Pthread_mutex_lock (&mutex); //Do work .Pthread_mutex_unlock (&mutex);}1. The Nslocknslock class uses a POSIX thread to implement its lock operation, and it is important to note that an unlock message must be sent within the same thread, or an indeterminate situation can occur. Nslock cannot be used to implement an iterative lock, because if a lock message occurs two times, the entire thread will be permanently locked. BOOL Moretodo=YES; Nslock*thelock =[[Nslock alloc] init]; .... while(Moretodo) {/*Do another increment of calculation*/    /*until there ' s no more to do.*/    if([Thelock Trylock]) {/*Update display used by all threads.*/[Thelock unlock]; }}2. @synchronized @synchronized is in objectiveThe simplest method of-c, as long as there is a objective-The C object can complete the thread synchronization operation. - (void) MyMethod: (ID) anobj{@synchronized (anobj) {//everything between the braces is protected by the @synchronized directive.It is important to note that @synchronized implicitly adds exception handling code, which automatically releases the mutex when an exception occurs, so there is some performance loss. 3. The Nsrecursivelocknsrecursivelock class defines a lock that can be fetched multiple times by the same thread without causing a deadlock. Nsrecursivelock can be used in recursive calls, but Nsrecursivelock can be fetched by other threads only if the locks that are acquired more than once are released. Nsrecursivelock*thelock =[[Nsrecursivelock alloc] init];voidMyrecursivefunction (intvalue) {[ThelockLock]; if(Value! =0)    {        --value;    Myrecursivefunction (value); } [Thelock unlock];} Myrecursivefunction (5);4. Nsconditionlocknsconditionlock defines a conditional mutex, which acquires a lock when the condition is established, and instead releases the lock. Because of this feature, conditional locks can be used in a specific sequence of processes, such as producers-consumer issues. IDCondlock =[[Nsconditionlock alloc] initwithcondition:no_data];//producer while(true) {[CondlockLock]; /*ADD data to the queue.*/[Condlock unlockwithcondition:has_data];} //Consumer while(true) {[Condlock lockwhencondition:has_data]; /*Remove data from the queue.*/[Condlock unlockwithcondition: (IsEmpty?No_data:has_data)]; //Process the data locally.The initial state of the conditional lock is no_data, so the producer thread acquires the lock at this time, and then sets the state to Has_data after the production is completed, and then the consumer thread discovers that the condition becomes has_data and then acquires the lock until the end of the consumption and then sets the status to No_ DATA. 5. Nsdistributedlocknsdistributedlock is a distributed lock across processes, and the underlying is a mutex that is implemented with a file system. Nsdistributedlock does not implement the Nslocking protocol, so there is no lock method that blocks the thread, instead of a non-blocking Trylock method. Nsdistributedlock is released only when the lock holder is explicitly released, that is, when the lock-holding app crashes, other apps cannot access the protected shared resources. 6. The Nsconditionnscondition class is a combination of mutexes and conditional locks that can be awakened by another thread when a thread waits for a signal to block. It is important to note that due to differences in operating system implementations, threads may be awakened even if the signal message is not sent in the code, so it is necessary to increase the predicate variable to ensure the correctness of the program. [CocoaconditionLock]; while(Timetodowork <=0) [cocoacondition wait]; Timetodowork--; //Do real work here .[cocoacondition unlock]; Wake in another thread: [CocoaconditionLock];timetodowork++; [Cocoacondition signal]; [Cocoacondition unlock];7. POSIX Conditions in Unix/a set of conditional mutex APIs is also available on the Linux platform://InitializeintPthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *attr); //Wait (will block)intPthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mut); //timed WaitintPthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mut,Const structTimespec *abstime); //Wake upintPthread_cond_signal (pthread_cond_t *cond); //broadcast wake-upintPthread_cond_broadcast (pthread_cond_t *cond); //destroyedintPthread_cond_destroy (pthread_cond_t *cond), like the Nscondition class, POSIX conditions also needs to be used with predicates to ensure program correctness. pthread_mutex_t mutex;pthread_cond_t condition; Boolean Ready_to_go=true; voidmycondinitfunction () {Pthread_mutex_init (&mutex); Pthread_cond_init (&condition, NULL);} voidmywaitonconditionfunction () {//Lock the mutex.Pthread_mutex_lock (&mutex); //If The predicate is already set, then the and loop is bypassed; //Otherwise, the thread sleeps until the predicate is set.     while(Ready_to_go = =false) {pthread_cond_wait (&condition, &mutex); }     //Do work .     (The mutex should stay locked.) //Reset the predicate and release the mutex.Ready_to_go =false; Pthread_mutex_unlock (&mutex);} voidsignalthreadusingcondition () {//at this point, there should is work for the other thread to do.Pthread_mutex_lock (&mutex); Ready_to_go=true; //Signal The other thread to begin work.Pthread_cond_signal (&condition); Pthread_mutex_unlock (&mutex);} References [1] Threading Programming Guidezhixingheyi-http://foredoomed.org

Lock and application in Objective-c -13-multithreading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.