There are several ways to solve the problem of mutex synchronization for multithreaded access to the same memory address in iOS:
Method One, @synchronized (ID anobject), (simplest method)
Automatically locks the parameter object to ensure code thread safety within the critical area
@synchronized (self)
{//
This code is mutually exclusive to other @synchronized (self)
/self to point to the same object
}
Method Two, Nslock
The Nslock object implements the Nslocking protocol, including several methods:
- Lock, add lock
- Unlock, unlock
- Trylock, try locking, and if it fails, it won't block the thread, just return no immediately
- Lockbeforedate: Temporarily blocks a thread (if no lock is acquired) before the specified date, and if the lock is not acquired at expiration, the thread is awakened and the function returns no immediately
Like what:
Nslock *thelock = [[Nslock alloc] init];
if ([Thelock lock])
{
//do something here
[Thelock unlock];
}
Method III, Nsrecursivelock, recursive lock
Nsrecursivelock, multiple invocations do not block threads that have acquired the lock.
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];
}
Method Four, Nsconditionlock, conditional lock
Nsconditionlock, conditional locks, you can set conditions
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 mode implementation, can cross process
- Use the Trylock method to get the lock.
- Release the lock with the unlock method.
If a process that acquires the lock hangs before releasing the lock, the lock is not released, and the lock can be forcibly acquired by Breaklock.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.