首页 > 解决方案 > 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;
}  

我可以使用这样的代码:

int *bla = (int*)calloc(1, sizeof(int));
*bla = 3;
set_report((void *)bla);

int *v = (int *)(void *)get_report();

我几乎找不到任何关于使用带有指针的原子的参考或文档,所以我对这段代码有一些疑问:

标签: catomic

解决方案


推荐阅读