回调问题

时间:2011-02-19 18:51:12

标签: c

基本上我试图建立一个调度员,但它失败了,因为它总是“!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;
}

任何帮助都是适当的

1 个答案:

答案 0 :(得分:3)

您的代码没有任何意义。你发射一个线程,然后永远循环尝试走g_events列表。但是,在启动时,它只有一个未初始化的节点,所以任何事情都可能发生!

此外(1),您的线程之间没有同步,所以即使您解决了上述问题,当人们尝试添加事件时,您可能会遇到令人讨厌的种族危险。

此外(2),你的两个线程都处于“忙等待”循环中,这会让你的CPU干涸。您需要研究一种机制,使您的线程在某些事物到达之前进入睡眠状态,例如信号量。