首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >InterlockedCompareExchange安卓系统崩溃问题

InterlockedCompareExchange安卓系统崩溃问题
EN

Stack Overflow用户
提问于 2019-09-20 06:07:51
回答 1查看 225关注 0票数 1

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

代码语言:javascript
运行
复制
    // 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位处理器

我试着用这种方式改变呼叫

代码语言:javascript
运行
复制
#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;
}

现在我在我的应用程序中遇到了一些引用错误和奇怪的行为,即使我使用我的新函数得到了相同的值,你有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-27 03:39:02

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

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

代码语言:javascript
运行
复制
#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进行陷阱),如果不同的线程并发访问这种未对齐的原子,它也不会以预期的方式运行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58019454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档