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;
}
我可以使用这样的代码:
int *bla = (int*)calloc(1, sizeof(int));
*bla = 3;
set_report((void *)bla);
int *v = (int *)(void *)get_report();
我几乎找不到任何关于使用带有指针的原子的参考或文档,所以我对这段代码有一些疑问:
- 在 C 中原子地进行指针交换时,这是正确的方法吗
- 根据我阅读的内容,在使用指针的原子方法(gcc stdatomic.h)时,我需要使用 uintptr_t。但我无法绕过关于强制转换为不匹配类型的警告。我应该忽略那些吗?
- 'aptr' 需要被声明为 volatile 吗?
解决方案
推荐阅读
- node.js - 了解 Revit 元素上传到 Forge 平台后的坐标系转换和引用
- python - Scikit Learn Count Vectorizer 找不到所有标记
- javascript - 如何使用 _.omit lodash 在 node.js 中省略列标题?
- ms-access - 访问数据宏从查询中获取值(自动编号)
- python - 图表不随下拉列表更新(Dash Plotly)
- android - 手机存储中创建的sqlite数据库文件的默认位置在哪里
- ruby-on-rails - ruby 如何拆分 (':') 并返回 2/3 拆分部分
- c# - 根据当前对象将 OrderBy Predicate 转换为 Where Predicate
- android - 与经典蓝牙配对后,我可以在不使用 GATT 连接的情况下向 ble 4.2 或 ble 5 模块发送数据吗
- php - 加载视图后如何执行函数