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

非 Y 不嫁゛ 提交于 2019-12-02 08:41: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 and the second one reads from it. How do i lock and unclock the threads to avoid crashes and keep the code thread safe ?

// Thread for writing data into mutable array 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer) {
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway);
    dispatch_source_set_event_handler(timer, ^{
        ...
        // Put data into ivar
        [mMutableArray addObject:someObject];
        ...
    });
    dispatch_resume(timer);
}

// Thread for reading from mutable array
dispatch_source_t timer1 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer1) {
    dispatch_source_set_timer(timer1, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway);
    dispatch_source_set_event_handler(timer1, ^{
        ...
        if (mMutableArray) {
            // Read data from ivar
            SomeObject* someobject = [mMutableArray lastObject];
        }
        ...
    });
    dispatch_resume(timer1);
}

回答1:


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




回答2:


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.




回答3:


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);


来源:https://stackoverflow.com/questions/11070947/gcd-how-to-write-and-read-to-variable-from-two-threads

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