liv2hak
liv2hak

Reputation: 14990

Advantages of a separate thread in C program

I have a capture program which in addition do capturing data and writing it into a file also prints some statistics.The function that prints the statistics

static void report(void)
{
         /*Print statistics*/
}

is called roughly every second using an ALARM that expires every second.So The program is like

void capture_program()
{


            while()
            {
                     /*Main loop*/
                     if(doreport)
                          report();
            }
}

The expiry of the timer sets the doreport flag.If this flag is set report() is called which clears the flag.

Now my question is

I am planning to move the reporting function to a separate thread.The main motivation to do this is that the reporting function executes some code that is under a lock.Now if another process is holding the lock,then this will block causing the capture process to drop packets.So I think it might be a better idea to move the reporting to a thread.

2) If I were to implementing the reporting in a separate thread,should I still have to use timers inside the thread to do reporting every second?

                         OR

Is there a better way to do that by making the thread wakeup at every 1 second interval

Upvotes: 0

Views: 118

Answers (1)

Huachao Huang
Huachao Huang

Reputation: 216

What are the advantages in moving the reporting function to a separate thread?

If your reporting function is trivial, for example, you just need to print some thing, I don't think a separate thread will help a lot.

If I were to implementing the reporting in a separate thread, should I still have to use timers inside the thread to do reporting every second?

You don't need timers, you can just go to sleep every second, like this:

static void report(void)
{
    while (1) {
        /*Print statistics*/
        sleep(1);
    }
}

Upvotes: 1

Related Questions