如何处理多个定时器信号

时间:2016-06-16 09:08:17

标签: c linux timer

@Autowired(required = false)
public final void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory)   {
   if (!this.externalSqlSession) {
   this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
   }
}

@Autowired(required = false)
public final void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
   this.sqlSession = sqlSessionTemplate;
   this.externalSqlSession = true;
}

在这段代码中,我制作了许多定时器,其中id由数组结构构成。

如果发生超时事件,则所有计时器共享一个timer_handler。但是我怎么知道哪个索引(t_id [index])超时了?

有可能吗?我的意思是我想知道哪个指数的超时发生了。

2 个答案:

答案 0 :(得分:1)

使用结构的简单示例:

struct timer_event_data
{
    timer_t id;
    size_t  index;  // Array index, not really needed IMO
    // Other possible data
};

#define NUMBER_TIMER_EVENTS 100

int main(void)
{
    struct timer_event_data timer_data[NUMBER_TIMER_EVENTS];

    for (size_t i = 0; i < NUMBER_TIMER_EVENTS; ++i)
    {
        // Initialize structure
        timer_data[i].index = i;

        // Start timer
        makeTimer(NULL, &timer_data[i], i + 1, 0);
    }

    // Main processing loop
    for (;;)
    {
        // ...
    }

    return 0;
}

void makeTimer(const char *name, struct timer_event_data *timer_data, unsigned sec, unsigned msec)
{
    ...
    te.sigev_value.sival_ptr = timer_data;
    timer_create(CLOCK_REALTIME, &te, &timer_data->id);
    ...
}

static void timer_handler( int sig, siginfo_t *si, void *uc ) 
{
    struct timer_event_data *timer_data = si->si_value.sival_ptr;
    // Use data in structure any way you want
}

答案 1 :(得分:0)

可以定义指向t_id第一个元素的全局指针:

timer_t * pt_id;

main()中初始化它:

timer_t t_id[100];
pt_id = t_id;

然后在timer函数内部计算所需的索引,方法是将差异取为数组:

  size_t tidx = tidp - pt_id - 1;