This is the 26th day of my participation in the August More Text Challenge

IOS development, various locks you know how much? Handhold takes you two ways to implement a read-write lock!

review

NSLock, NSCondtion, NSRecursiveLock, NSCondition, NSCondtion, NSRecursiveLock, NSCondition, NSCondtion, NSCondtion, NSRecursiveLock, NSCondition

Multithreading in iOS (I) – Processes and threads

IOS low-level exploration of multithreading (II) – Threads and locks

IOS low-level exploration of multithreading (3) – GCD

IOS low-level exploration of multithreading (4) – GCD queue

IOS bottom exploration of multithreading (five) – GCD different queue source analysis

IOS bottom exploration of multithreading (six) – GCD source analysis (sync function, async asynchronous function)

IOS low-level exploration of multithreading (seven) – GCD source analysis (cause of deadlock)

IOS bottom exploration of multithreading (eight) – GCD source analysis (function synchronization, asynchrony, singleton)

IOS bottom exploration of multithreading (nine) – GCD source analysis (fence function)

IOS low-level exploration of multithreading (10) – GCD source analysis (semaphore)

IOS bottom exploration of multithreading (11) – GCD source analysis (scheduling group)

IOS Low-level exploration of multithreading (12) – GCD source code analysis (event source)

Multithreading of iOS low-level exploration (13) – How much do you know about the types of locks?

Multithreading in iOS (14) — What do you know about @synchronized locks?

IOS bottom exploration of multithreading (15) – @synchronized source code analysis

IOS low-level exploration of multithreading (16) — lock analysis (NSLock, NSCondtion, NSRecursiveLock, NSCondition)

Analysis of locks (NSLock, NSCondition, NSRecursiveLock) via Swift Foundation source code

1. What is read/write lock?

Before we begin, what is a read/write lock?

  • Read-write lockIt’s actually a special kind ofspinlocks, which divides visitors to shared resources intoThe readerandwriter, readers only for shared resourcesRead access, the writer needs to carry out on the shared resourceThe write operation.
  • This lock is relative tospinlocksCan improve concurrency, because in multiprocessor systems, it allows simultaneousMultiple readerstoAccessing shared Resources, the maximum possible number of readers isActual number of logical cpus.
  • The writer isexclusiveA read/write lock can have only one writer or more readers at a timeNumber of CPURelated), but cannot have both readers and writers, and preemption invalidates while the read/write lock is held.
  • ifRead-write lockCurrently there is noThe readerThere is no writer, so the writer canImmediately getRead and write the lock, otherwise it mustThe spinThere, until there were no writers or readers.
  • ifRead-write lockThere is nowriter, then the reader can immediately acquire the read-write lock, otherwise the readerMust beThe spin is there until the writerThe release ofThis read-write lock.
  • Only one thread can occupy it at a timeWrite modeRead/write lock, but can have multiple threadsAt the same timeBecause of this property, when the read-write lock is in the write-lock state, all threads attempting to lock the lock will be locked before the lock is unlockedblocking.
  • When read/write locks inRead lock statusIs available to all threads trying to lock it in read modeAccess to theBut ifthreadYou want to do this lock in write modelockIt has to be until allThread release lock.
  • The usual case is whenRead-write lockIn aRead mode locked stateIf there is another threadTrying toLock in write mode. Read/write locks usually doblockingA subsequent read-mode lock request, thus avoiding a read-mode lockLong timeWhile waiting for the write mode lock requestBlocked for a long time.
  • Read-write lockSuitable for situations where data structures are read much more often than written. Because the read mode lock can be shared, while the write mode lock means exclusive, so the read/write lock is also calledShared-exclusive lock

So how do we encapsulate a read-write lock?

What is the core function of read/write locks? There is no doubt about it: read more and write more.

  • Read moreThis allows multiple threads to read the memory space.
  • A single writeIt means that only one thread can write to this space at a time, and if there are multiple writes, the data will be messed up, which we can’t allow.
  • Write and write mutually exclusiveB can write only after A has written.
  • Read and write should be mutually exclusiveWhen A is writing, B can’t read it.
  • Read and write can not block the main thread, can not affect the normal program operation.

Now that all the attention points and function points are clear, so no more nonsense, let’s get to work! This will be implemented in two ways: pThread API and GCD API.

2. Pthread implements read/write locks

So, first of all, we use pthread to implement, simulate the situation of train tickets, the code is as follows:

// Note that the header file is imported
#import <pthread.h>

@interface ViewController(a)

@property (nonatomic.assign) NSUInteger trainTickets;// Number of train tickets
@property (nonatomic.assign) pthread_rwlock_t jpLock;/ / lock

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	self.trainTickets = 0;
	[self jp_Test];
}
Copy the code
  • A read operation
	/ / read method- (void)jP_read{
		/ / read lock
	pthread_rwlock_rdlock(&_jpLock);
	sleep(1);
	NSLog(@" The number of train tickets read is :%zd".self.trainTickets);
		/ / unlock
	pthread_rwlock_unlock(&_jpLock);
}
Copy the code
  • The write operation
	/ / write method- (void)jP_write{
		/ / write lock
	pthread_rwlock_wrlock(&_jpLock);

	sleep(1);
	NSLog(@" Number of train tickets after writing :%zd"The + +self.trainTickets);
		/ / unlock
	pthread_rwlock_unlock(&_jpLock);
}

Copy the code
  • Let’s see how it works out. Okay

The code works perfectly. It works perfectly! The result is normal, no confusion!

  • pthread API

  • pthread_rwlock_t lock; / / structure

  • pthread_rwlock_init(&lock, null); / / initialization

  • pthread_rwlock_rdlock(&lock); / / read lock

  • pthread_rwlock_tryrdlock(&lock); // Read attempts to lock

  • pthread_rwlock_wdlock(&lock); / / write lock

  • pthread_rwlock_trywdlock(&lock); // Write attempts to lock

  • pthread_rwlock_unlock(&lock); / / unlock

  • pthread_rwlock_destory(&lock); / / destroy

3. GCD implements read/write lock

Above 👆 has used pthread to implement read and write lock, so now we are more familiar with GCD to implement it!

  • GCD implementation code is as follows:

  • The GCD implementation results are as follows:

The result is the same as the result of pthread. Here is not more analysis, code comments are available, I believe we all understand!

4. To summarize

  • The core function of read/write locks isRead write
  • Write and write mutually exclusive
  • Read and write should be mutually exclusive
  • Read and writeDo not block the main thread, cannot affect the normal program operation.

More content continues to be updated

🌹 if you like, give it a thumbs up 👍🌹

🌹 feel harvest, can come to a wave, collection + attention, comment + forward, so as not to find me next time 😁🌹

🌹 welcome everyone to leave a message exchange, criticism and correction, learn from each other 😁, improve themselves 🌹