Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory model spec in pthreads

Are there any guarantees on when a memory write in one thread becomes visible in other threads using pthreads?

Comparing to Java, the Java language spec has a section that specifies the interaction of locks and memory that makes it possible to write portable multi-threaded Java code.

Is there a corresponding pthreads spec?

Sure, you can always go and make shared data volatile, but that is not what I'm after.

If this is platform dependent, is there a de facto standard? Or should another threading library be used?

like image 377
Tobias Ritzau Avatar asked Feb 19 '23 22:02

Tobias Ritzau


1 Answers

POSIX specifies the memory model in 4.11 Memory Synchronization:

Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location while another thread of control may be modifying it. Such access is restricted using functions that synchronize thread execution and also synchronize memory with respect to other threads. The following functions synchronize memory with respect to other threads:

  • fork()
  • 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()

The pthread_once() function shall synchronize memory for the first call in each thread for a given pthread_once_t object.

The pthread_mutex_lock() function need not synchronize memory if the mutex type if PTHREAD_MUTEX_RECURSIVE and the calling thread already owns the mutex. The pthread_mutex_unlock() function need not synchronize memory if the mutex type is PTHREAD_MUTEX_RECURSIVE and the mutex has a lock count greater than one.

Unless explicitly stated otherwise, if one of the above functions returns an error, it is unspecified whether the invocation causes memory to be synchronized.

Applications may allow more than one thread of control to read a memory location simultaneously.

like image 156
R.. GitHub STOP HELPING ICE Avatar answered Feb 28 '23 05:02

R.. GitHub STOP HELPING ICE