nslock/nsrecursivelock/nsconditionlock/@synchronized

Source: Internet
Author: User

nslock/nsrecursivelock/nsconditionlock/@synchronized  http://blog.sina.com.cn/s/blog_8c87ba3b0101ok8y.html   uses the Nslock class      implements a simple mutex in Nslock in the Cocoa program. The interfaces for all locks (including nslock) are actually defined through the Nslocking protocol, which defines the lock and unlock methods. You use these methods to obtain and release the lock.      In addition to the standard locking behavior, the Nslock class also adds Trylock and lockbeforedate: methods. Method Trylock attempts to acquire a lock, but it does not block the thread if the lock is not available. Instead, it simply returns No. The Lockbeforedate: Method attempts to acquire a lock, but if the lock is not obtained within the specified time, it causes the thread to become nonblocking from the blocking state (or return no).      The following example shows that you can be an Nslock object to assist in updating a visual explicit, and its data structure is computed by multiple threads. If the thread does not have an immediate lock, it simply continues the calculation until it can get a lock and then update the explicit.      bool Moretodo = Yes;     nslock *theLock = [[NSLock alloc] Init ];     ...     while (Moretodo) {                             if ([Thelock trylock]) {            &nbSp;              [thelock unlock];          }     }4.6.3 using @synchronized Directive   The     @synchronized directive is a convenient way to create a mutex in the Objective-c code. @synchronized directives do the same work as other mutexes (it prevents different threads from acquiring the same lock at the same time). In this case, however, you do not need to create a mutex or lock object directly. Instead, you simply need to use the Objective-c object as a token for the lock, as shown in the following example:      -(void) MyMethod: (ID) anobj      {          @synchronized (anobj)           {              //everything between the braces is protected by the @synchronized directive.     & nbsp;   }     }     The object created to the @synchronized directive is a unique identifier used to distinguish the protection block. If you execute the above method in two different threads, each time a different object is passed to the Anobj parameter in a thread, then each time it will have its lock and continue processing, and the middle is not blocked by other threads. However, if youBy passing the same object, one line in multiple threads routines the lock first, while the other threads are blocked until the first thread finishes its critical section.      as a precaution, @synchronized block implicitly adds an exception-handling routine to protect the code. The processing routine releases the mutex automatically when the exception is thrown. This means that in order to use the @synchronized directive, you must enable exception handling in your code. If you do not want an implicit exception-handling routine to bring additional overhead, you should consider using a lock class. 4.6.4 use other cocoa locks      The following sections describe the use of cocoa other types of locks. • Use Nsrecursivelock objects      Locks defined by the Nsrecursivelock class can be obtained multiple times on the same thread without causing deadlocks. A recursive lock keeps track of how many times it was successfully acquired. Each successful acquisition of the lock must balance the call to lock and unlock the operation. Only when all locked and unlocked operations are balanced does the lock really get released to other threads.      as its name suggests, this type of lock is often used in a recursive function to prevent recursion from causing a blocking thread. You can similarly use him to invoke functions in non-recursive situations where the semantics of these functions require them to use locks. The following is a simple recursive function that acquires a lock in recursion. If you do not use the Nsrecursivelock object in the code, the thread will deadlock when the function is called again.                nsrecursivelock  *thelock = [[Nsrecursivelock alloc] init];     void MyRecursiveFunction (int Value) {         [thelock lock];          if (Value! = 0) {   &NBsp;         --value;              myrecursivefunction (value);          }        [thelock unlock];     }      myrecursivefunction (5);     Note: Because a recursive lock will not be released until all locks are called balanced using an understanding lock operation, So you have to carefully weigh the potential impact on performance of deciding whether to use locks. Holding a lock for a long time will cause other threads to block until the recursion is complete. If you can rewrite your code to eliminate recursion or eliminate the use of a recursive lock, you may get better performance. • A mutex is defined using the Nsconditionlock object     nsconditionlock object. You can use specific values to lock and unlock. Do not confuse this type of lock and condition (see "Conditions" section). Its behavior and conditions are somewhat similar, but their implementation is very different.      Typically, when multithreading needs to perform tasks in a specific order, you can use a Nsconditionlock object, such as when one thread produces data and the other consumes data. When the producer executes, the consumer uses the conditions specified by your program to acquire the lock (the condition itself is a defined value that you define). When the producer finishes, it unlocks the lock and sets the condition of the lock to the appropriate shaping value to wake up the consumer thread, after which the consuming thread continues to process the data. The     nsconditionlock lock and unlock method can be used in any combination. For example, you can use Unlockwithcondition: and lock messages, or use lockwhencondition: and unlock messages. Of course, later combinations can unlock a lock but may not release any lines waiting for a certain condition valueRide.      The following example shows how a producer-consumer problem can be handled using conditional locks. Imagine an application that contains a queue of data. A producer thread adds data to the queue, and the consumer thread pulls the data out of the queue. The producer does not need to wait for a specific condition, but it must wait for the lock to be available so that it can safely add data to the queue.      id Condlock = [[Nsconditionlock alloc] initwithcondition:no_data];      while (True) {         [condlock lock];                  [condlock unlockwithcondition:has_data];     }     because the value of the Initialize condition lock is no_data, The producer thread can get the lock without problems when it is initialized. It adds the queue data and sets the condition to Has_data. In subsequent iterations, the producer thread can add the arriving data to the queue, regardless of whether the queue is empty or still has data. The only way to get it into a block is when a consumer thread is charging the queue to fetch the data.      because the consumer thread has to have data to handle, it waits for the queue with a specific condition. When the producer puts the data into the queue, the consumer thread is awakened and acquires its lock. It can fetch data from the queue and update the status of the queue. The following code shows the basic structure of the consumer threading loop.      while (true) {         [condlock Lockwhencondition:has_data];       &nBsp;          [condlock unlockwithcondition: (isEmpty? No_data:has_data)];         //Process the DATA locally.      } using Nsdistributedlock objects      The Nsdistributedlock class can be used by multiple applications on multiple hosts to restrict access to certain shared resources, such as a file. The lock itself is an efficient mutex that is implemented using a file system project, such as a file or directory. For an available Nsdistributedlock object, the lock must be written by all programs that use it. This usually means putting it on file systems, which can be accessed by all applications running on the computer.      Unlike other types of locks, Nsdistributedlock does not implement the Nslocking protocol, all of which do not have a lock method. A lock method will block the execution of the thread and require the system to poll the lock at a predetermined speed. To implement this constraint in your code, Nsdistributedlock provides a Trylock method and lets you decide whether to poll.      because it is implemented using a file system, a Nsdistributedlock object is not freed unless its owner explicitly releases it. If your program crashes while a user is distributing a lock, other clients cannot access the protected resource. In this case, you can use the Breadlock method to break the existing lock so that you can get it. However, you should always avoid breaking the lock unless you are sure that the owning process is dead and it is impossible to release the lock again.      like other types of locks, when you use the Nsdistributedlock object, you can release it by calling the Unlock method.

nslock/nsrecursivelock/nsconditionlock/@synchronized

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.