The premise

In iOS development, mutex is used most of the time, but when there is too much read and too little write, mutex can waste the time to unlock, so use read and write locks.

Read/write locks have the following features:

  • Only one thread can write at a time.
  • Multiple threads are allowed to read at the same time.
  • Both write and read operations are not allowed at the same time.

A, pthread_rwlock_init

pthread_rwlock_t lock; // Initialize lock pthread_rwlock_init(&lock, NULL); // read-lock pthread_rwlock_rdlock(&lock); // read - try to lock pthread_rwlock_tryrdlock(&lock); // write - lock pthread_rwlock_wrlock(&lock); // write - try to lock pthread_rwlock_trywrlock(&lock); / / unlock pthread_rwlock_unlock (& lock); / / destroyed pthread_rwlock_destroy (& lock);Copy the code

Second, the dispatch_barrier_async

“Dispatch_barrier_async” is also called “fence block” or “synchronization point”. It is simply a synchronization point in a parallel queue. Asynchronous tasks after dispatch_barrier_async have to wait until the dispatch_barrier_async execution is complete. Can be executed.

Dispatch_queue_t queue = dispatch_queue_create("LLDebugtool.com", DISPATCH_QUEUE_CONCURRENT); // perform some reads dispatch_sync(queue, ^{// Read action1.}); dispatch_sync(queue, ^{ // Read action2. }); . Dispatch_barrier_async (queue, ^{// Write action.}); Dispatch_sync (queue, ^{// Read action3.}); dispatch_sync(queue, ^{ // Read action4. });Copy the code