gpt4 book ai didi

c++ - pthreads 中的内存模型规范

转载 作者:太空宇宙 更新时间:2023-11-04 04:39:17 24 4
gpt4 key购买 nike

使用 pthread 是否可以保证一个线程中的内存写入何时在其他线程中可见?

与 Java 相比,Java 语言规范有一个 section that specifies the interaction of locks and memory这使得编写可移植的多线程 Java 代码成为可能。

是否有相应的 pthreads 规范?

当然,您总是可以让共享数据变得不稳定,但这不是我想要的。

如果这取决于平台,是否有事实上的标准?还是应该使用另一个线程库?

最佳答案

POSIX 在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.

关于c++ - pthreads 中的内存模型规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28119507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com