简体   繁体   English

计时器回调的长程序

[英]Long precedure in timer's callback

I am working on a timer now, timers are maintained by a linked list.Like this: 我现在正在使用计时器,计时器由一个链表维护。

struct timer
{
    struct timer* prev;
    struct timer* next;
    struct timespec start;
    struct timespec interval;
    void* par; 
    int (*handler) (void* par);
};

Then I use a thread called dispatch to sleep and pick timers from the list.The code is simplified as below: 然后我使用一个名为dispatch的线程来睡眠并从列表中选择计时器,代码简化如下:

//just pseudo code here
void dispatch() {
    for (;;) {
        while (list_empty()) {
            wait();
        }
        timer* ptr = listhead();
        if (timer_begin(ptr)) {
            ptr->handler(ptr->par);
            list_pop_front();
        }
    }
}

Question: When there is a long precedure in the callback function handler (say the handler function costs 500ms to execute, then dispatch stucks), the rest timers in the list may not be processed in time.So do we need a thread pool here?Or is there any other advices? 问题:当回调函数handler存在较长的过程时(例如,处理程序函数执行需要500毫秒,然后dispatch阻塞),列表中的其余计时器可能无法及时处理。那么我们这里需要thread pool吗?还是还有其他建议?

The problem of long duration tasks interleaved with short duration tasks is a fundamental problem of real-time (and near-real-time) systems. 长时任务与短时任务交错的问题是实时(和近实时)系统的基本问题。 Having a separate thread to handle longer running tasks, and delegating longer tasks to a second thread is a good solution. 有一个单独的线程来处理运行时间较长的任务,并将较长的任务委派给第二个线程是一个很好的解决方案。 But is your long-running task waiting on io, or just heavy processing? 但是,您的长时间运行的任务是否正在等待io或只是繁重的处理?

Should the delay be caused by asynchronous processing (waiting on io, for example), You might split the work into a 'top-half' and a 'bottom-half', where the 'top-half' dispatches the io request, and then schedules a 'bottom-half' to check for the results. 如果延迟是由异步处理引起的(例如,在io上等待),则可以将工作分为“上半部分”和“下半部分”,其中“上半部分”调度io请求,并且然后安排“下半部分”检查结果。 Alternatives are to handle the signal from the response, possibly with a promise (really interesting technique). 替代方案是处理来自响应的信号,可能带有承诺(非常有趣的技术)。

Should the delay be cause by a processing heavy task, you might still be able to use a similar technique, by forming your compute heavy task in such a way that it 'yields' periodically. 如果延迟是由处理繁重的任务引起的,则您仍然可以使用类似的技术,通过以定期“屈服”的方式形成计算繁重的任务。 Threading is better, but may not be available in some embedded environments. 线程化效果更好,但在某些嵌入式环境中可能不可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM