gpt4 book ai didi

android - InterlockedCompareExchange Android 崩溃问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:32:47 29 4
gpt4 key购买 nike

我正在尝试使用 c++( native )为 64 位处理器运行 android 应用程序,当我执行这些函数时,我遇到了崩溃问题(总线错误)

    // returns the resulting incremented value
#define InterlockedIncrement(pInt) __sync_add_and_fetch(pInt, 1)

// returns the resulting decremented value
#define InterlockedDecrement(pInt) __sync_sub_and_fetch(pInt, 1)

// returns the initial value
#define InterlockedExchangeAdd(pInt,nAdd) __sync_fetch_and_add(pInt,nAdd)

// returns the initial value of the pInt parameter.
#define InterlockedCompareExchange(pInt,nValue,nOldValue) __sync_val_compare_and_swap(pInt,nOldValue,nValue)

我阅读了一些关于这些函数的信息,它似乎只适用于 32 位处理器

我试过这样改叫

#include <atomic>
#include <iostream>

inline BOOL InterlockedCompareExchange(volatile INT* pInt, INT nValue, INT nOldValue)
{
std::atomic<INT> ai;
ai = *pInt;
return ai.compare_exchange_strong(nOldValue, nValue,
std::memory_order_release,
std::memory_order_relaxed);
}

inline LONG InterlockedExchange(volatile LONG* pInt, LONG nValue)
{
std::atomic<LONG> ai;
LONG nOldValue;
ai = *pInt;
nOldValue = *pInt;
while (!ai.compare_exchange_strong(nOldValue, nValue,
std::memory_order_release,
std::memory_order_relaxed));
*pInt = nValue;
return nValue;
}

inline LONG InterlockedIncrement(volatile LONG* pInt)
{
std::atomic<LONG> ai;
ai = *pInt;
ai.fetch_add(1, std::memory_order_relaxed);
*pInt = ai;
return ai;
}

inline LONG InterlockedDecrement(volatile LONG* pInt)
{
std::atomic<LONG> ai;
ai = *pInt;
ai.fetch_sub(1, std::memory_order_relaxed);
if (ai < 0)
ai = 0;
*pInt = ai;
return ai;
}

inline LONG InterlockedExchangeAdd(volatile LONG* pInt, LONG nValue)
{
std::atomic<LONG> ai;
ai = *pInt;
ai.fetch_add(nValue, std::memory_order_relaxed);
if (ai < 0)
ai = 0;
*pInt = ai;
return ai;
}

现在,即使我使用我的新函数获得相同的值,我的应用程序中也出现了一些引用错误和奇怪的行为,知道吗?

最佳答案

在某些平台上,我猜这是在 arm 上的情况,总线错误通常意味着您有未对齐的访问(在您的情况下,您的原子 32 位或 64 位整数变量之一未对齐分别为 4 或 8 字节边界。)

例如,这里是显式未对齐的原子访问:

#include <atomic>
#include <string.h>

int main()
{
char buf[16];
memset( buf, 0, sizeof(buf) );

std::atomic<int> * pi = (std::atomic<int> *)(((intptr_t)buf & ~3) + 5);

pi->fetch_add(1);

return 0;
}

即使像这样的代码似乎可以工作(即不会陷入 SIGBUS 或 SIGSEGV),如果不同线程同时访问这种未对齐的原子,它也不会以预期的方式运行。

关于android - InterlockedCompareExchange Android 崩溃问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58019454/

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