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

标签 c++ c multithreading pthreads shared-memory

使用 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/

相关文章:

c - C 中的二叉搜索树出现奇怪的故障

c - 如何阻止 pthread 从 main 打印全局变量然后继续 pthread?

c# - 防止事件处理程序中 InvokeRequired 的必要性

c++ - 值如何存储在 char 中

c - 在创建霍夫曼树时哪个节点在增加权重时向左或向右

c++ - 如何以编程方式选择 QTableView 中的下一行

c - C 文件中使用相同的 goto 标签但功能不同

python - 打印/追加以列出线程模块中线程函数的值

c++ - 试图在 C++ 中将一个文本文件拆分为多个文本文件

c++ - 如何在现代 C++ 中使用生成器初始化 const 容器?