Zäta
Zäta

Reputation: 322

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

Upvotes: 1

Views: 883

Answers (2)

caf
caf

Reputation: 239081

Under the pthreads model, the readers do need to perform a synchronisation operation as well. This can be a pthread_mutex_lock() / pthread_mutex_unlock() pair in both the readers and writer as you've described, or alternatively metalfox's suggestion of a reader-writer lock.

Upvotes: 1

metalfox
metalfox

Reputation: 6731

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.

Upvotes: 1

Related Questions