Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex in Obj-c / Cocoa

I'm pretty new to multithreaded programming & cocoa.

I'm going to need a lock to access/modify a NSMutableArray iVar. What's the simpliest way to do it ?

And while I'm here, do you guys have some reading about multithreaded programming with Obj-c/Cocoa ? Thx.

like image 785
Matthieu Riegler Avatar asked Dec 21 '22 19:12

Matthieu Riegler


2 Answers

Using the @synchronized block:

@synchronized(MyArray)
{
    // thread safe code
}

This block is not recognized by Xcode at times, but trust me, it works!

For more information, you can read this article.

like image 89
Richard J. Ross III Avatar answered Jan 08 '23 23:01

Richard J. Ross III


An alternative method is to use GCD and serial queues.

For your NSArray property, write accessors that use a private serial queue. to set, and fetch the values from the backing store. Since serial queues Are FIFO, and will run the blocks sequentially this provides thread safe access to the property.

like image 23
Abizern Avatar answered Jan 09 '23 00:01

Abizern