Understanding of iOS multi-thread programming locks and ios multi-thread programming

Source: Internet
Author: User

Understanding of iOS multi-thread programming locks and ios multi-thread programming

1. Examples of Mutual Exclusion

In a multi-threaded environment, no matter which function method can be executed simultaneously in multiple threads. However, when using shared variables, or when the execution file outputs or graphs are drawn, multiple threads can execute at the same time to get strange results.
For example, if you use the integer global variable totalNumber to accumulate the number of data processed, what results will be obtained when you execute this method in a multi-threaded environment to execute the following addition calculation?

- (void)addNumber:(NSInteger)n{    totalNumber +=n;}

When the two threads run simultaneously, of course, with the support of the OS function, the threads sometimes get the CPU execution right while running, and sometimes get the suspended execution right, the execution result deviates from the expected result because the read, update, and write operations of values are executed simultaneously by multiple threads.

Ii. Lock

The NSLock class can be used to allow multiple threads to use shared resources such as global variables with mutual exclusion.
The lock has the properties that can be obtained and used by only one thread at a time. The obtained lock is called "Lock" and the release lock is called "unlock".
The lock uses the class method alloc and the initialization tool init to create and initialize the lock. However, the lock should be created before the program starts multi-thread execution.

NSLock * countLock = [[NSLock alloc]init];

The methods for obtaining and Releasing locks are defined in the NSLocking protocol.

-(Void) lock; // If the lock is in use, the thread enters the sleep state. If the lock is not in use, the lock status changes to in use and the thread continues to execute. -(Void) unlock; // set the lock to unused. In this case, if there is a sleeping thread waiting for the lock resource, wake it up.

In this Code, when the lock is obtained from execution 1 of a thread to execution 2 of this thread to release the lock, other threads will enter the sleep state when execution 1, and the code in the critical section cannot be executed. After the lock is released, select a thread in the sleeping thread during execution 1. After the thread acquires the lock, it enters the critical section for execution.

-(Void) addNumber :( NSInteger) n {[aLock lock]; ----------------------- 1 totalNumber + = n; // The critical section [aLock unlock]; ---------------------- 2}

After a lock is locked, an unlock must be executed. And the lock and unlock must be executed in the same thread.

3. deadlock

The relationship between threads and locks must be carefully considered at the beginning of the design. If the lock is incorrectly used, not only cannot execute mutex as expected, but may also cause multiple threads to be unable to execute, that isDeadlock (deadlock)Status.


Thread 1.png
Thread 2.png


Thread 1 occupies File A and is processing it. On the way, it needs to occupy file B. On the other hand, thread 2 occupies file B, and there is A need to occupy file A on the way. Thread 1 wants to obtain the lock bLock to process file B, but it has been obtained by thread 2. Similarly, the lock aLock that thread 2 wants to obtain is also occupied by thread 1. In this case, thread 1 and thread 2 enter the sleep state at the same time, and neither side can jump out of this state.

4. Try to get the lock

The NSLock class not only acquires and releases locks, but also checks whether the lock is obtained. With these functions, you can perform other operations when the lock cannot be obtained.

-  (BOOL) tryLock

Use the receiver to try to obtain a lock. If the lock can be obtained, YES is returned. If the lock cannot be obtained, the thread does not enter the sleep state, and NO is returned directly and continues execution.

5. Conditional lock

NSConditionLock instance initialization, set the value specified by the condition parameter. NSConditionLock.

- (instancetype)initWithCondition:(NSInteger)condition

Return the value set in the lock.

@property (readonly) NSInteger condition;

If the lock is in use, the thread enters the sleep state.
When the lock is not in use, if the lock value is consistent with the condition value of the parameter, the lock status is changed to being used and then continues to be executed. If the lock is inconsistent, the thread enters the sleep state.

- (void)lockWhenCondition:(NSInteger)condition;

Set the value specified by the condition parameter in the lock. Set the lock to not in use. In this case, if a thread is waiting to obtain the lock and is in sleep state, wake it up.

- (void)unlockWithCondition:(NSInteger)condition;

If the lock is not used and the lock value is the same as the condition parameter, YES is returned when the lock is obtained. If the lock cannot be obtained, NO is returned and the thread continues to execute the lock.

- (BOOL)tryLockWhenCondition:(NSInteger)condition;

When using lock, unlock, and trylock, you can obtain the lock and release the lock without worrying about the lock value.

6. NSRecursiveLock, recursive lock

After a thread acquires the lock, when the thread releases the lock, the thread that wants to obtain the lock will enter sleep. When NSLock is used, if the thread that has obtained the lock wants to obtain the lock again without releasing it, the thread will also sleep. However, since there is no thread from sleep, This is a deadlock.

[ALock lock]; [aLock lock]; // deadlock [aLock unlock]; [aLock unlock];

To solve this problem, you can use the NSRecursiveLock class lock. The thread that owns the lock won't enter the deadlock even if the same lock is obtained multiple times. However, other threads certainly cannot obtain the lock. The lock is released when the number of obtained attempts is the same as the number of released attempts.

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.