Objective-c in different ways to achieve lock (a) -12-multithreading

Source: Internet
Author: User
Tags gcd mutex semaphore

Different ways to achieve lock in Objective-C (1)

Why do you need to use locks? Of course, you who are familiar with multithreading will naturally not be unfamiliar with it.

Did you use the lock mechanism well in your code? Do you know several ways to implement locks?

Today, let's discuss the locks implemented in several different ways in Objective-C. Before that, we first build a test class. Imagine it is a shared resource of ours. Method1 and method2 are mutually exclusive.


@implementation TestObj
 
-(void) method1
{
    NSLog (@ "% @", NSStringFromSelector (_cmd));
}
 
-(void) method2
{
    NSLog (@ "% @", NSStringFromSelector (_cmd));
}
 
@end
1. Lock using NSLock


// in the main thread
TestObj * obj = [[TestObj alloc] init];
NSLock * lock = [[NSLock alloc] init];
 
// Thread 1
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    [lock lock];
    [obj method1];
    sleep (10);
    [lock unlock];
});
 
// Thread 2
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    sleep (1); // To ensure that the code of thread 2 is executed after
    [lock lock];
    [obj method2];
    [lock unlock];
});
Do you see the printed result? You will see that after thread 1 is locked, thread 2 will wait until thread 1 sets the lock to unlock before executing method 2 method.

NSLock is the most basic lock object provided by Cocoa, which is what we often use. In addition to the lock and unlock methods, NSLock also provides tryLock and lockBeforeDate: two methods, the first method will try to lock, if the lock is not available Used (already locked), it just won't block the thread and returns NO. lockBeforeDate: The method will try to lock before the specified Date. If it cannot be locked before the specified time, it returns NO.

2.Locks built using the synchronized keyword

Of course, in Objective-C you can also use the @synchronized instruction to quickly achieve locks:


// in the main thread
TestObj * obj = [[TestObj alloc] init];
 
// Thread 1
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    @synchronized (obj) {
        [obj method1];
        sleep (10);
    }
});
 
// Thread 2
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    sleep (1);
    @synchronized (obj) {
        [obj method2];
    }
});
The obj used by the @synchronized instruction is the unique identifier of the lock. Only when the identifiers are the same, is the mutual exclusion satisfied. If @synchronized (obj) in thread 2 is changed to @synchronized (other), just the thread 2 will not be Blocking, the advantage of the @synchronized instruction to implement the lock is that we do not need to explicitly create a lock object in the code to implement the lock mechanism, but as a precautionary measure, the @synchronized block will implicitly add an exception handling routine To protect the code, the processing routine will automatically release the mutex when an exception is thrown. So if you don't want the extra overhead of implicit exception handling routines, you can consider using lock objects.

3. The lock realized by pthread_mutex_t in C language


// in the main thread
TestObj * obj = [[TestObj alloc] init];
 
__block pthread_mutex_t mutex;
pthread_mutex_init (& mutex, NULL);
 
// Thread 1
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    pthread_mutex_lock (& mutex);
    [obj method1];
    sleep (5);
    pthread_mutex_unlock (& mutex);
});
 
// Thread 2
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    sleep (1);
    pthread_mutex_lock (& mutex);
    [obj method2];
    pthread_mutex_unlock (& mutex);
});
pthread_mutex_t is defined in pthread.h, so remember #include <pthread.h>
4. "Lock" using GCD
In the above code, we have used GCD's dispatch_async method to build multi-threads. In fact, GCD also provides a signal mechanism. Using it, we can also build a "lock" (in essence, the semaphore and There are differences in locks, the specific differences are the differences between participating semaphores and mutex locks):


// in the main thread
TestObj * obj = [[TestObj alloc] init];
dispatch_semaphore_t semaphore = dispatch_semaphore_create (1);
 
// Thread 1
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    dispatch_semaphore_wait (semaphore, DISPATCH_TIME_FOREVER);
    [obj method1];
    sleep (10);
    dispatch_semaphore_signal (semaphore);
});
 
// Thread 2
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    sleep (1);
    dispatch_semaphore_wait (semaphore, DISPATCH_TIME_FOREVER);
    [obj method2];
    dispatch_semaphore_signal (semaphore);
});
As for the effect of the code, of course, it is exactly the same as the previous example. Regarding the signal mechanism, you will not be unfamiliar with C programming. For more information about dispatch_semaphore_t in GCD, you can jump to this previous part of this blog. Article: Introduction to GCD (3): Dispatch Sources

Well, the above are some of the ways I have listed to implement locks. Of course, locks are also used with multithreading in most cases. I wo n’t go into details about multithreaded programming.

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.