对64位字进行32位比较和交换
32bit compare and swap on a 64 bit word
假设我有一个64位字(high32,low32),我对一个32位变量(比如low32)执行__sync_val_compare_and_swap
。在两个线程同时尝试在high32和low32上执行CAS的情况下,它们都能成功吗?
在windows 64位上,无论对齐和缓存线是否交叉(除非我的测试应用程序有错误),相邻int上的CAS总是成功。我只测试了windows 7,64位。
编辑:这可能是CAS在所有现代英特尔芯片上工作的方式,而不考虑操作系统。我在一辆I7上跑步。
#include <stdio.h>
#include <windows.h>
volatile __declspec(align(64)) char a[128];
int _nAlign = 0;
DWORD WINAPI ThreadProc(LPVOID lpThreadParameter)
{
auto iElem = (int)lpThreadParameter;
volatile auto* p = (int*)(a + _nAlign + sizeof(int) * iElem);
for (long long i = 0; i < 1000000000; ++i) {
int nOld = *p, nNew = nOld + 1;
if (InterlockedCompareExchange((DWORD*)p, (DWORD)nNew, (DWORD)nOld) != nOld)
return 1;
}
return 0;
}
int main(int argc, char* argv[])
{
if (argc == 2)
_nAlign = atoi(argv[1]);
HANDLE aThread[2];
for (int i = 0; i < 2; ++i) {
aThread[i] = CreateThread(NULL, 0, ThreadProc, (LPVOID)i, 0, NULL);
SetThreadAffinityMask(aThread[i], 1<<(2*i)); // hyperthreading is on, so make sure on actual separate cores
}
WaitForMultipleObjects(2, aThread, true, INFINITE);
DWORD aCode[2];
if (!GetExitCodeThread(aThread[0], &aCode[0]) || !GetExitCodeThread(aThread[1], &aCode[1]))
printf("GetExitCodeThread failedn");
if (aCode[0] || aCode[1])
printf("CAS failedn");
else
printf("CAS Succeededn");
return 0;
}
相关文章:
- shell排序中的交换和比较
- 不正确的比较和交换计数器输出用于快速排序功能
- 原子值的部分比较和完全交换
- 跟踪选择排序中的交换和比较次数
- 如何在C 中实施简单的比较和交换共享计数器
- 为什么比较和交换操作同时存在免费函数和成员函数?
- 计数交换/比较合并排序算法的数字
- 通过比较数组中的相邻元素来计算交换次数
- 使用C++原子库,我应该使用什么样的内存顺序进行加载,然后进行比较交换
- 128位比较和交换固有
- std::atomic<int*>::load 应该做一个比较和交换循环吗?
- 互锁。比较交换<Int> 使用大于或小于而不是相等
- 如何将比较和交换用于任何共享数据结构的免等待互斥
- 你能用lambda比较器交换std::队列吗
- C++11比较和交换获取/释放语义
- 原子比较运算符(无交换)
- C++中比较和交换
- 比较和交换三个原子变量
- 如何在C++中获取快速排序的移动,交换和比较计数
- 比较交换原子操作vs加载链接/存储条件操作