c++ - Interoperabilty between C and C++ atomics
问题描述
Suppose, I have a task that might be cancelled from another thread. The task is performed in a C function, another thread runs C++ code. How do I do that?
Rough example.
C:
void do_task(atomic_bool const *cancelled);
C++:
std::atomic_bool cancelled;
…
do_task(&cancelled);
For now, I created a file atomics.h
with the following content:
#ifdef __cplusplus
#include <atomic>
using std::atomic_bool;
#else
#include <stdatomic.h>
#endif
It appears to work, but I don't see any guarantees for that. I wonder, if there is a better (correct) way.
解决方案
To side-step all ABI issues you may like to implement a C function that is called from C++ and operates on that atomic_bool
. This way your C++ code doesn't need to know anything about that global variable and its type:
In an .h
file:
#ifdef __cplusplus
extern "C" {
#endif
void cancel_my_thread(void);
int is_my_thread_cancelled(void);
#ifdef __cplusplus
}
#endif
And then in a .c
file:
#include <stdatomic.h>
static atomic_bool cancelled = 0;
void cancel_my_thread(void) {
atomic_store_explicit(&cancelled, 1, memory_order_relaxed);
}
int is_my_thread_cancelled(void) {
return atomic_load_explicit(&cancelled, memory_order_relaxed);
}
The C++ code would include that headed and call cancel_my_thread
.
推荐阅读
- r - 在哪里将进度条代码插入嵌套循环?
- php - mysql查询中表名的语法错误
- angular - 如果后端刷新令牌成功,如何做可见组件
- sql - 如何使用 Vertica AVG [分析]
- javascript - Woocommerce,如何编辑“已添加到购物车”消息并实现通知系统
- javascript - 如何将库 (p5.js) 添加到 Stackblitz IDE?
- angular - Angular 7将firebase UserInfo映射到自定义用户模型
- javascript - 我怎样才能让这个虚拟键盘上的按钮在点击后消失
- javascript - 多选输出中的换行符(引导选择)
- java - JSF,Primefaces LazyDataModel - 更新行而不调用加载方法