c - 如何链接/连接回调、观察者和对象
问题描述
我是 C 的新手,并试图弄清楚实现以下内容:
- 我有一些事件的回调/观察者数组
- 每个回调都会对回调中的事件/数据做一些不同的事情
- 如何在 python 中执行“this->”、“self”或与回调“绑定”。
- 这一切都是在多线程环境中执行的,生产者/消费者共享数据的方式。
- 如何处理同一类型的多个消费者?例如,在 C++ 中,我使用了带有条件变量的类作为成员,因为回调与对象相关联,所以它起作用了。但是在 C 中,我该怎么做呢?因此,在下面的示例中,我将如何通知 obj_1 和 obj_2 有要处理的事件。每个都可以有一个队列或事件缓冲区,但随后又回到#3,如何将队列/缓冲区链接到回调?
这是一个真正实现的简单示例
#include <stdlib.h>
#include <stdio.h>
/* Different objects, have different data members and implementations */
struct MyObject {
int data;
};
struct MyOtherObject {
double data;
};
void MyObjectCallback(int event, struct MyObject* o) {
/* On an int event MyObject does something with the data */
o->data *= event + event;
}
void MyOtherObjectCallback(int event, struct MyOtherObject* o) {
/* On an int event MyOtherObject does something with the data */
o->data = sqrt(o->data) * event;
}
typedef void (*callback)(int);
/* All the callbacks for an "int" event */
static callback all_callbacks[10] = {NULL};
int main() {
struct MyObject obj_1, obj_2;
obj_1.data = 1;
obj_2.data = 2;
struct MyOtherObject obj_3;
obj_3.data = 3;
/* How do I link the MyObjectCallbacks to all_callbacks? */
/* Somewhere an "int" event has occured, notify all callbacks */
int actual_event = 42;
for (int i = 0; i < 10; i++) {
/* This doesnt work cause all_callbacks has no idea of MyObjects */
if (all_callbacks[i] != NULL) all_callbacks[i](event);
}
}
解决方案
推荐阅读
- c# - EF6。确保“System.Data.Entity.Properties.Resources.PowerShell.resources”正确嵌入或链接到程序集“EntityFramework”
- hyperledger-fabric - ./byfn.sh up -l 节点失败
- linux - 如何在 windows 和 linux 之间可移植地模块限定 powershell cmdlet 名称
- git - Git补丁子模块
- python - Selenium 代码无法从 Chrome 中捕获表格
- performance - Powershell:改进 LDIF 文件到 CSV 的转换
- docker - 参数化 docker exec psql -c 命令
- python - 无法使用 pip 安装 Twilio:为 twilio 运行 setup.py install ... 错误错误:命令出错,退出状态为 1:
- python - 在 Spark 工作人员上更改 PYSPARK_PYTHON
- java - 字符串操作 - 将第二个单词的字符删除到第一个单词