Glenn Cooper
Glenn Cooper

Reputation: 167

C Programming - Fire Process every nth minute

I'm working on a large project where I need to monitor the process of a struct every nth minute.

Each instance of the struct may have it's own length of time for the process to do what it's going to do.

For an example, let's say I monitoring a client connection, struct client.

When the client has been instantiated, I would be looking to incorporate a method such as:

void add_Client_Monitor (client_t * client, int seconds)

The add_Client_Monitor should then be able to create a timer event that would fire after the seconds stipulated, and also act on the client struct, i.e. by such a method like:

void timer_Update_Client(client_t * client)

Thanks

Upvotes: 0

Views: 113

Answers (1)

rcmgleite
rcmgleite

Reputation: 1321

You could use a thread pool for that(like these one github.com/Pithikos/C-Thread-Pool or these one github.com/mbrossard/threadpool). In your add_Client_Monitor function, you could pass a job to a thread pool with the specific function you want to run. As a simple example:

#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;
}

I haven't looked at the entire code of these thread pool implementations, but they seem correct. And of course there are many others that you can use.

Upvotes: 1

Related Questions