多线程程序中操作原子性.docVIP

  • 4
  • 0
  • 约 10页
  • 2017-08-03 发布于河南
  • 举报
/2010/04/15/atomic-operation-in-multithreaded-application/ 多线程程序中操作的原子性 0. 背景 HYPERLINK /wiki/Atomic_operation \o 原子操作 原子操作 就是不可再分的操作。在多线程程序中原子操作是一个非常重要的概念,它常常用来实现一些同步机制,同时也是一些常见的多线程Bug的源头。本文主要讨论了三个问题:1. 多线程程序中对变量的读写操作是否是原子的?2. 多线程程序中对Bit field(位域)的读写操作是否是线程安全的?3. 程序员该如何使用原子操作? 1. 多线程环境下对变量的读写操作是否是原子的? 我们先从一道很热门的百度笔试题讲起。很多人讲不清楚其背后的原理,我们就对它进行一下剖析(其实这个题目有点歧义,后面我们会讲到): 以下多线程对int型变量x的操作,哪几个需要进行同步:( ) A. x=y; B. x++; C. ++x; D. x=1; 要彻底理解这个问题,我们首先需要从硬件讲起。以常见的X86 CPU来说,根据Intel的 HYPERLINK /design/processor/manuals/253668.pdf \o 参考手册 参考手册 ,它基于以下三种机制保证了多核中加锁的原子操作(8.1节): (1)Guaranteed atomic operations (注:8.1.1节有详细介绍) (2)Bus locking, using the LOCK# signal and the LOCK instruction prefix (3)Cache coherency protocols that ensure that atomic operations can be carried out on cached data structures (cache lock); this mechanism is present in the Pentium 4, Intel Xeon, and P6 family processors 这三个机制相互独立,相辅相承。简单的理解起来就是 (1)一些基本的内存读写操作是本身已经被硬件提供了原子性保证(例如读写单个字节的操作); (2)一些需要保证原子性但是没有被第(1)条机制提供支持的操作(例如read-modify-write)可以通过使用”LOCK#”来锁定总线,从而保证操作的原子性 (3)因为很多内存数据是已经存放在L1/L2 cache中了,对这些数据的原子操作只需要与本地的cache打交道,而不需要与总线打交道,所以CPU就提供了cache coherency机制来保证其它的那些也cache了这些数据的processor能读到最新的值(关于cache coherency可以参加我的 HYPERLINK /2010/03/06/why-should-programmer-care-about-sequential-consistency-rather-than-cache-coherence/ \o 一篇博文 一篇博文 )。 那么CPU对哪些(1)中的基本的操作提供了原子性支持呢?根据Intel手册8.1.1节的介绍: 从Intel486 processor开始,以下的基本内存操作是原子的: ? Reading or writing a byte(一个字节的读写) ? Reading or writing a word aligned on a 16-bit boundary(对齐到16位边界的字的读写) ? Reading or writing a doubleword aligned on a 32-bit boundary(对齐到32位边界的双字的读写) 从Pentium processor开始,除了之前支持的原子操作外又新增了以下原子操作: ? Reading or writing a quadword aligned on a 64-bit boundary(对齐到64位边界的四字的读写) ? 16-bit accesses to uncached memory locations that fit within a 32-bit data bus(未缓存且在32位数据总线范围之内的内存地址的访问) 从P6 family processors开始,除了之前支持的原子操作又新增了以下原子操作: ? Unaligned 16-, 32-, and 64-bit accesses to cached memory that fit within a cache line(对单个cache line中缓存地址的未对齐的16/32/64位访问) 那么

文档评论(0)

1亿VIP精品文档

相关文档