Using C/Pthreads: do shared variables need to be volatile?

前端 未结 13 943
迷失自我
迷失自我 2020-11-28 06:03

In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that t

13条回答
  •  情书的邮戳
    2020-11-28 06:22

    POSIX 7 guarantees that functions such as pthread_lock also synchronize memory

    https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11 "4.12 Memory Synchronization" says:

    The following functions synchronize memory with respect to other threads:

    pthread_barrier_wait()
    pthread_cond_broadcast()
    pthread_cond_signal()
    pthread_cond_timedwait()
    pthread_cond_wait()
    pthread_create()
    pthread_join()
    pthread_mutex_lock()
    pthread_mutex_timedlock()
    pthread_mutex_trylock()
    pthread_mutex_unlock()
    pthread_spin_lock()
    pthread_spin_trylock()
    pthread_spin_unlock()
    pthread_rwlock_rdlock()
    pthread_rwlock_timedrdlock()
    pthread_rwlock_timedwrlock()
    pthread_rwlock_tryrdlock()
    pthread_rwlock_trywrlock()
    pthread_rwlock_unlock()
    pthread_rwlock_wrlock()
    sem_post()
    sem_timedwait()
    sem_trywait()
    sem_wait()
    semctl()
    semop()
    wait()
    waitpid()
    

    Therefore if your variable is guarded between pthread_mutex_lock and pthread_mutex_unlock then it does not need further synchronization as you might attempt to provide with volatile.

    Related questions:

    • Does guarding a variable with a pthread mutex guarantee it's also not cached?
    • Does pthread_mutex_lock contains memory fence instruction?

提交回复
热议问题