我正在尝试使用c++ (原生)为安卓64位处理器运行一个应用程序,当我执行这些函数时,我遇到了崩溃问题(总线错误)。
// 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;
}
现在我在我的应用程序中遇到了一些引用错误和奇怪的行为,即使我使用我的新函数得到了相同的值,你有什么想法吗?
发布于 2019-10-27 03:39:02
在一些平台上,我猜在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进行陷阱),如果不同的线程并发访问这种未对齐的原子,它也不会以预期的方式运行。
https://stackoverflow.com/questions/58019454
复制相似问题