gpt4 book ai didi

回调问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:43 24 4
gpt4 key购买 nike

基本上我正在尝试制作一个调度程序,但它失败了,因为它总是“!event->callback_function”,我的代码:

#include "event.h"
#include "memory.h"
#include "thread.h"

#include <stdio.h>
#include <time.h>
#include <assert.h>

bool running;

typedef struct Event {
event_callback_t cb;
time_t delay;
void* p;
struct Event* next;
} Event;

Event* g_events;

void _remove_event __P((Event**, Event *));
void event_dispatch_internal __P(());
void add_event_internal __P((Event**, Event *));

void
event_dispatch()
{
g_events = (Event *)MyMalloc(sizeof(*g_events));
create_thread((callback_t)event_dispatch_internal, (void *)NULL);
}

void
add_event_internal(Event** events, Event* event)
{
event->next = *events;
*events = event;
}

void
add_event(callback, param, delay)
event_callback_t callback;
void *param;
time_t delay;
{
Event* event;
event = (Event *)MyMalloc(sizeof(*event));
assert(0 != event);

event->delay = time(NULL) + delay;
event->p = param;
event->cb = callback;
add_event_internal(&g_events, event);
}

void
_remove_event(Event** events, Event* event)
{
event = *events;
*events = event->next;
}

void
event_dispatch_internal()
{
#ifdef _DEBUG
fprintf(stderr, "Events started\n");
#endif
while (true) {
Event* tmp;
for (tmp = g_events; tmp; tmp = tmp->next) {
if (time(NULL) >= tmp->delay) {
tmp->cb(tmp->p);
#ifdef _DEBUG
fprintf(stderr, "Executed event %p:%u\n", (void *)tmp, (unsigned int)tmp->delay);
#endif
_remove_event(&g_events, tmp);
}
}
}
}

它崩溃了,但是当我那样做时:

            for (tmp = g_events; tmp; tmp = tmp->next) {
if (time(NULL) >= tmp->delay) {
if (!tmp->cb) {
tmp->cb(tmp->p);
#ifdef _DEBUG
fprintf(stderr, "Executed event %p:%u\n", (void *)tmp, (unsigned int)tmp->delay);
#endif
} else {
fprintf(stderr, "Couldnt execute event %p:%u\n", (void *)tmp, (unsigned int)tmp->delay);
}
}
}

它总是给出“无法执行事件 blabla”

虽然我这样调用它:

void test_(void *);

void
test_(void *p)
{
fprintf(stderr, "test(): %d\n", *(int *)p);
}

int main()
{
int test;
test = 5;
event_dispatch();
add_event(test_, (void *)&test, 1);
do { } while (1);
return 0;
}

感谢任何帮助

最佳答案

您的代码没有任何意义。您启动一个线程,然后它会一直循环尝试遍历 g_events 列表。然而,在启动时,其中只有一个未初始化的节点,所以任何事情都有可能发生!

此外 (1),您的线程之间没有同步,因此即使您解决了上述问题,当人们尝试添加事件时,您也可能会陷入严重的竞争危险。

此外 (2),您的两个线程实际上都处于“忙等待”循环中,这会耗尽您的 CPU。您需要研究一种机制,使您的线程休眠直到有东西到达,例如信号量。

关于回调问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5052810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com