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

感情迁移 提交于 2019-12-02 03:00:35
Valerio

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

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!