2015-11-08 74 views
0

我正在处理一个大型项目,我需要每隔n分钟监视一次结构的进程。C编程 - 每隔n分钟执行一次消息处理

结构的每个实例可能都有它自己的时间长度,以便进程执行它将要执行的操作。

举一个例子,假设我监视客户端连接,struct client。

当客户端已被实例化,我将寻求结合的方法,如:

void add_Client_Monitor (client_t * client, int seconds) 

然后add_Client_Monitor应该能够创建秒规定之后,将触发一个计时器事件,也作用于客户结构,通过这样的方法,即像:

void timer_Update_Client(client_t * client) 

感谢

+0

您可以使用pthreads创建一个[timer](http://forums.devshed.com/programming-42/using-pthread-create-stopwatch-timer-592599.html)。 – erip

回答

1

你可以使用一个线程池(像这样的一个github上.com/Pithikos/C-Thread-Pool或这一个github.com/mbrossard/threadpool)。 在您的add_Client_Monitor函数中,您可以将作业传递给具有要运行的特定函数的线程池。 作为一个简单的例子:

#include "thpool.h" 

typedef struct monitor_func_args { 
    client_t* client; 
    int seconds; 
} monitor_func_args; 

void* client_monitor_func(void* args){ 
    struct timeval timeout; 
    timeout.tv_sec = ((monitor_func_args*) args)->seconds; 
    timeout.tv_usec = 0; 
    while(1) { 
     // Do your stuff 
     select (0 ,NULL, NULL, NULL, &timeout); // "sleep" 
    } 
} 

void add_client_monitor (threadpool pool, client_t * client, int seconds) { 
    monitor_func_args* args = (monitor_func_args*) malloc(sizeof(monitor_func_args)); 
    args->client = client; 
    args->seconds = seconds; 
    thpool_add_work(pool, client_monitor_func, (void*) args); 
} 


int main(){ 
    threadpool thpool = thpool_init(10); // pool with 10 threads 

    client_t* client; // get it from somewhere 
    int timeout // get it from somewhere 

    add_client_monitor(thpool, &client, timeout) 

    thpool_destroy(thpool); 
    return 0; 
} 

我没有看过这些线程池实现的全部代码,但他们似乎是正确的。 当然还有很多其他的你可以使用。

+0

谢谢,这是一个很大的帮助。所以从本质上说,它不是创建一个计时器本身的情况,而是启动一个可以触发另一个函数的线程,并且在该函数内你可以让它进入睡眠状态。 –

+0

是的,这是一般的想法。没问题:)干杯 – rcmgleite

+0

最后一个问题,我可能有成千上万的这些线程同时运行。我应该设置什么池大小?该服务器有12个内核。线程本身监视客户端音频连接并每隔n分钟注入30秒广告。这些线程可能会在95%的时间内闲置,但在不同的时间单独忙碌 –

相关问题