首页 > 解决方案 > 如何链接/连接回调、观察者和对象

问题描述

我是 C 的新手,并试图弄清楚实现以下内容:

  1. 我有一些事件的回调/观察者数组
  2. 每个回调都会对回调中的事件/数据做一些不同的事情
  3. 如何在 python 中执行“this->”、“self”或与回调“绑定”。
  4. 这一切都是在多线程环境中执行的,生产者/消费者共享数据的方式。
  5. 如何处理同一类型的多个消费者?例如,在 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);
  }
}

标签: ccallbackproducer-consumer

解决方案


推荐阅读