Understanding of the lock for iOS multithreaded programming

Source: Internet
Author: User

I. Examples of mutually exclusive needs

In a multithreaded environment, no matter which function method can be executed concurrently in multiple threads. However, when using shared variables, or when performing file output or drawing drawings, the simultaneous execution of multiple threads can result in strange results.
For example, using the integer global variable totalnumber to accumulate the number of processed data, in order to perform the following addition calculation, what would be the result of executing the method in a multithreaded environment?

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

When two threads execute simultaneously, of course, under the support of the OS function, the thread will be executed by the CPU in the process of running, and sometimes be suspended execution, so the execution result will deviate from the result we expect as a whole, because the read, update and write operation of the value is executed by multithreading simultaneously.

Second, the lock

To enable shared resources such as global variables to be mutually exclusive among multiple threads, you can use the Nslock class.
A lock has a nature that allows only a single thread to get and use it at a time. Acquiring a lock is called "locking", and releasing a lock is called "unlocking".
Locks are created and initialized using the class method alloc and initializer init. However, the lock should be created before the program starts multithreaded execution.

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

Both the method of obtaining the lock and the method of releasing the lock are defined in the Protocol nslocking.

-  (void) lock;//如果锁正被使用,则线程进入休眠状态;如果锁没被使用,则锁的状态变为正被使用,线程继续执行。-  (void) unlock;//将锁设置为没被使用,此时如果有等待该锁资源的正在休眠的线程,则将其唤醒。

In this code, when execution of a 1 lock from a thread executes a 2 release lock on the thread, the other thread will go into hibernation at 1 o'clock and cannot execute the critical section code. After the lock is freed, a thread in the dormant thread is selected at execution 1 o'clock, and the thread is taken to the critical section after the lock is taken.

- (void)addNumber:(NSInteger)n{  lock];-----------------------1  totalNumber +=n;          //临界区  [aLock unlock];--------------------2}

Once a lock is locked, a unlock must be executed once. and lock and unlock must be executed on the same thread.

Third, deadlock

The relationship between threads and locks must be carefully considered at the beginning of the design. If a lock is used incorrectly, not only does the mutex not perform as expected, but it can also cause multiple threads to fall into a state that cannot be executed, that is, the deadlock (deadlock) state.


Thread 1.png
Thread 2.png


Thread 1 occupies file A and is being processed, and it is necessary to occupy file B on the way. On the other hand, thread 2 occupies file B, on the way there is a need to occupy file a. Thread 1 wants to get the lock block in order to process file B, but it has been obtained by thread 2. Similarly, the lock alock that thread 2 wants to acquire is also occupied by thread 1. In this case, thread 1 and thread 2 go into hibernation at the same time, and neither side can jump out of that state.

Iv. trying to acquire a lock

The Nslock class not only obtains locks and release locks, but also checks for the ability to obtain locks. With these features, you can perform additional processing when locks are not available.

-  (BOOL) tryLock

The receiver attempts to obtain a lock, and if the lock can be obtained returns Yes, not available, unlike lock processing, the thread does not go into hibernation and returns no and continues execution.

Five, Conditional lock

Nsconditionlock instance initialization, sets the value specified by the parameter condition. The specified initializer for the nsconditionlock.

- (instancetype)initWithCondition:(NSInteger)condition

This returns the value set in the lock

@property (readonly) NSInteger condition;

If the lock is in use, the thread goes into hibernation.
When the lock is not in use, if the lock value is the same as the value of the parameter condition, the state of the lock is changed to be in use, then continues execution, and if not, the thread goes into hibernation.

- (void)lockWhenCondition:(NSInteger)condition;

Sets the value specified in the lock for the parameter condition. Sets the lock to not being used, which wakes up if there is a thread waiting to get the lock and is in a dormant state.

- (void)unlockWithCondition:(NSInteger)condition;

The lock is not used and the lock value is the same as the parameter condition, the lock is obtained and yes is returned, the lock is not entered into hibernation, and the thread continues execution.

- (BOOL)tryLockWhenCondition:(NSInteger)condition;

Locks and release locks can be obtained when using the method lock, Unlock, trylock, and do not care about the value of the lock.

Six, Nsrecursivelock, recursive lock

When a thread obtains a lock, the thread that wants to acquire the lock goes into hibernation while the thread releases the lock. When using a nslock lock, the thread also goes into hibernation if the thread that has acquired the lock wants to acquire the lock again without releasing it. However, because there are no threads waking from hibernation, this is a deadlock.

lock];[aLock lock];//这里发生死锁[aLock unlock];[aLock unlock];

To resolve this situation, you can use the lock of the Nsrecursivelock class, and the thread that owns the lock will not enter a deadlock even if the same lock is obtained multiple times. However, other threads certainly cannot get the lock. When the number of gains and the number of releases are consistent, the lock is released.

Understanding of the lock for iOS multithreaded programming

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.