gpt4 book ai didi

c++ - InterlockedCompareExchange128 用法

转载 作者:行者123 更新时间:2023-11-27 23:22:55 31 4
gpt4 key购买 nike

我正在尝试使用 MS VC++ Intrinsic InterlockedCompareExchange128 函数。

作为一个 hello-world,我正在尝试将一个 16 字节的地址与其自身进行比较,并将其替换为其他内容。这编译,但它不工作 - 地址不与新值交换。 const_cast 用于使其编译(否则它会因无法转换 volatile 而哭泣)。

typedef struct t_node
{
volatile __int64 arr[2];
}node;

int main()
{

node *a = new node();

a->arr[0] = 100;
a->arr[1] = 1;

__int64 i = 200;
__int64 j = 500;

char r = _InterlockedCompareExchange128(a->arr, i,j, const_cast<__int64*>(&a->arr[0]));

cout<<endl<<"Interlocked Compare Res: "<<r;

cin.get();
return 0;
}

最佳答案

来自documentation :

unsigned char _InterlockedCompareExchange128(
__int64 volatile * Destination,
__int64 ExchangeHigh,
__int64 ExchangeLow,
__int64 * ComparandResult
);

[in, out] ComparandResult
Pointer to an array of two 64-bit integers (considered as a 128-bit field) to compare with the destination. On output, this is overwritten with the original value of the destination.

因此,在伪代码中发生的事情:

if(ComparandResult != Destination)
{
temp = Destination
Destination = ExchangeHigh:ExchangeLow
ComparandResult = temp
}

Destination == ComparandResult(你的情况)是:

if(ComparandResult != Destination)
{
temp = Destination
Destination = ExchangeHigh:ExchangeLow
Destination = temp
}

这是一个 nop。
此外,在同一页中还有一条注释:

Note
The value of ComparandResult is always overwritten. After the lock instruction, this intrinsic immediately copies the initial value of Destination to ComparandResult. For this reason, ComparandResult and Destination should point to separate memory locations to avoid unexpected behavior.

关于c++ - InterlockedCompareExchange128 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547284/

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