lockingpthreadsmutexunlockshared-resource

How to handle shared resources with pthread mutex


I have a question regarding mutex and pthreads.

If there is a shared flag, lets call it (F1). And there are multiple threads. But only one thread (T1) can raise/cease the flag and all other threads (T2..Tn) only reads or pulls the status.

Is it enough if T1 uses mutex_lock/mutex_unlock when the flag F1 will be set with a new value? Should all other threads also use mutex_lock/mutex_unlock even that they are only going to read the status from F1?

Exemple1:

    T1()
    {
        while(Running)
        {
            pthread_mutex_lock(&lock);
            F1 = true;
            pthread_mutex_unlock(&lock);
        }
    }

    T2()
    {
        while(Running)
        {
            if(F1) {
                /* Do something */
            }
        }
    }



Exemple2:

    T1()
    {
        while(Running)
        {
            pthread_mutex_lock(&lock);
            F1 = true;
            pthread_mutex_unlock(&lock);
        }
    }

    T2()
    {
        while(Running)
        {
            pthread_mutex_lock(&lock);
            if(F1) {
                /* Do something */
            }
            pthread_mutex_unlock(&lock);
        }
    }

Solution

  • You can use the single-writer-multiple-readers idiom.

    Reading:

    pthread_rwlock_rdlock(&rwlock);
    

    Writing:

    pthread_rwlock_wdlock(&rwlock);
    

    If your use case is as simple as the example you posted, you might consider a lock-free version involving atomic flags.