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

前端 未结 3 1144
自闭症患者
自闭症患者 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);
    

提交回复
热议问题