微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以原子方式交换C中的指针

如何解决以原子方式交换C中的指针

我需要线程向控制线程(星形拓扑)报告驻留在堆上的数据结构。我不想为此使用锁,而是通过原子交换指向此数据结构的指针来做到这一点。所以我有一个设置和获取报告的方法

_

我可以使用如下代码

static atomic_uintptr_t aptr = ATOMIC_VAR_INIT((uintptr_t)NULL);

void set_report(void *newreport)
{
    // swap the report pointer atomically
    uintptr_t prev = atomic_exchange( &aptr,(uintptr_t)newreport);
    // if prev is not NULL we need to destroy it
    if ( prev != (uintptr_t)NULL )
    {
        // destroy the memory it is pointing to
        free((void *)prev); //  there seems to be no way of avoiding a compiler warning here
                            //  about casting to a non-matching type :S
    }
}

uintptr_t get_report()
{
    // swap the report pointer atomically with NULL
    uintptr_t report = atomic_exchange( &aptr,(uintptr_t)NULL);
    // we Now own report so the caller must destroy when finished with it
    // unless it's null of course
    return report;
}  

我几乎找不到任何有关将原子与指针一起使用的参考文献或文档,因此我对此代码有一些疑问:

  • 在C语言中自动进行指针交换时,这是正确的方法吗?
  • 根据我的阅读,在将原子方法用于指针(gcc stdatomic.h)时,我需要使用uintptr_t。但是我无法避免有关强制转换为不匹配类型的警告。我应该忽略那些吗?
  • 是否需要将“ aptr”声明为易失性?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。