当一个C P U从内存读取一个字节时,它不只是取出一个字节,它要取出足够的字节来填入高速缓存行。高速缓存行可能包含32(老式cpu)、64、128字节,这要根据cpu而定。高速缓存行的作用是为了提高C P U运行的性能。通常情况下,应用程序只能对一组相邻的字节进行处理。如果这些字节在高速缓存中,那么C P U就不必访问内存总线,而访问内存总线需要多得多的时间。
// Determine the cache line size for the host CPU. //为各种CPU定义告诉缓存行大小 #ifdef _X86_ #define CACHE_ALIGN 32 #endif #ifdef _ALPHA_ #define CACHE_ALIGN 64 #endif #ifdef _IA64_ #define CACHE_ALIGN ?? #endif #define CACHE_PAD(Name, BytesSoFar) \ BYTE Name[CACHE_ALIGN - ((BytesSoFar) % CACHE_ALIGN)] struct CUSTINFO { DWORD dwCustomerID; // Mostly read-only char szName[100]; // Mostly read-only //Force the following members to be in a different cache line. //这句很关键用一个算出来的Byte来填充空闲的告诉缓存行 //如果指定了告诉缓存行的大小可以简写成这样 //假设sizeof(DWORD) + 100 = 108;告诉缓存行大小为32 //BYTE[12]; //作用呢就是强制下面的数据内容与上面数据内容不在同一高速缓存行中。 CACHE_PAD(bPad1, sizeof(DWORD) +100); int nBalanceDue; // Read-write FILETIME ftLastOrderDate; // Read-write //Force the following structure to be in a different cache line. CACHE_PAD(bPad2, sizeof(int) +sizeof(FILETIME)); };