GCD : How to write and read to variable from two threads

前端 未结 3 1145
自闭症患者
自闭症患者 2021-01-23 07:29

this may sound a newbie question anyway Im new to GCD,

I\'m creating and running these two following threads. The first one puts data into ivar mMutableArray

相关标签:
3条回答
  • 2021-01-23 08:05

    I've used mutexes in my project and I'm quite happy with how it works at the moment.

    Create the mutex and initialise it

    pthread_mutex_t *mutexLock;
    pthread_mutex_init(&_mutex, NULL);
    

    Then put the lock around your code, once the second thread tries to get the lock, it will wait until the lock is freed again by the first thread. Note that you still might want to check if the first thread is actually the one writing to it.

    pthread_mutex_lock(self_mutex);
    {
        ** Code here
    }
    pthread_mutex_unlock(self_mutex);
    
    0 讨论(0)
  • 2021-01-23 08:06

    You are using it wrong, by locking access to the variables you are simply losing any benefit from GCD. Create a single serial queue which is associated to the variables you want to modify (in this case the mutable array). Then use that queue to both write and read to it, which will happen in guaranteed serial sequence and with minimum locking overhead. You can read more about it in "Asynchronous setters" at http://www.fieryrobot.com/blog/2010/09/01/synchronization-using-grand-central-dispatch/. As long as your access to the shared variable happens through its associated dispatch queue, you won't have concurrency problems ever.

    0 讨论(0)
  • 2021-01-23 08:11

    You can still use @synchronized on your critical sections with GCD

    0 讨论(0)
提交回复
热议问题