问题描述
我需要线程向控制线程(星形拓扑)报告驻留在堆上的数据结构。我不想为此使用锁,而是通过原子交换指向此数据结构的指针来做到这一点。所以我有一个设置和获取报告的方法。
_
我可以使用如下代码:
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 (将#修改为@)