There are several ways to troubleshoot multi-threaded access to the same memory address in iOS for mutual exclusion synchronization issues:
Method One, @synchronized (ID anobject), (the simplest method)
Automatically locks the parameter objects to ensure code thread safety within the critical area
[CPP]View Plaincopyprint? < param name= "wmode" value= "Transparent" >
- @synchronized (self)
- {
- //This code is mutually exclusive to other @synchronized (self)
- //Self points to the same object
- }
Method Two, Nslock
The Nslock object implements the Nslocking protocol, which contains several methods:
Lock, plus lock
Unlock, unlocking
Trylock, attempts to lock, if it fails, does not block the thread, but returns no immediately.
Lockbeforedate:, temporarily blocks the thread before the specified date (if no lock is acquired), if the lock is not acquired at maturity, the thread is awakened, and the function immediately returns no
Like what:
[CPP]View Plaincopyprint? < param name= "wmode" value= "Transparent" >
- Nslock *thelock = [[Nslock alloc] init];
- if ([Thelock lock])
- {
- //do something here
- [Thelock unlock];
- }
method Three, Nsrecursivelock, recursive lock
Nsrecursivelock, multiple calls do not block the thread that has acquired the lock.
[CPP]View Plaincopyprint?
- Nsrecursivelock *thelock = [[Nsrecursivelock alloc] init];
- void myrecursivefunction (int value)
- {
- [Thelock Lock];
- if (value! = 0)
- <span style="FONT-SIZE:14PX;" > </span>{
- –value;
- Myrecursivefunction (value);
- }
- [Thelock unlock];
- }
- Myrecursivefunction (5);
Method Four, Nsconditionlock, conditional lock
Nsconditionlock, conditional lock, can set conditions
[CPP]View Plaincopyprint?
- Public part
- ID condlock = [[Nsconditionlock alloc] initwithcondition:no_data];
- //Line Cheng, producer
- While (true) {
- [Condlock Lockwhencondition:no_data];
- //Production data
- [Condlock Unlockwithcondition:has_data];
- }
- //Thread two, consumer
- While (true) {
- [Condlock Lockwhencondition:has_data];
- //Consumption
- [Condlock Unlockwithcondition:no_data];
- }
Method Five, Nsdistributedlock, distribution lock
Nsdistributedlock, distributed lock, file way implementation, can cross-process
Use the Trylock method to obtain the lock.
Use the Unlock method to release the lock.
If a process that acquires a lock is hung before releasing the lock, the lock will not be released until the lock can be forcibly acquired through Breaklock.