Panteleev Dima
Panteleev Dima

Reputation: 185

linux pthread running in a loop for specified time (avoiding signals)

hello what i want do is: thread (pthread.h) need to execute code in a while loop for some period of time that will be defined at run time
after that the thread will finish correctly the last loop and continue for some other work. right now I am using signals: This is the loop

setTimer(sec);
while(flag)
{
   //do some work
}
// continue to run

and i use signal to call for function that will set flag to false:

void setTimer(int sec)
{
  struct sigaction sa;
  struct itimerval timer;

  memset (&sa, 0, sizeof (sa));
  sa.sa_handler = &alarm_end_of_loop; // this is the function to change flag to false
  sigaction (SIGVTALRM, &sa, NULL);

  timer.it_value.tv_sec = sec;
  timer.it_value.tv_usec = 0;

  timer.it_interval.tv_sec = 0;
  timer.it_interval.tv_usec = 0;


  setitimer (ITIMER_REAL, &timer, NULL);
}

void alarm_end_of_loop()
{
flag = 0; //flag is global but only one thread will access it
}

My question is there a way to avoid using signals?

Upvotes: 1

Views: 1147

Answers (1)

Stefan Weiser
Stefan Weiser

Reputation: 2292

Seems to be a timeout pattern.

double get_delta_time_to_now(const time_t timeout_time)
{
    time_t now;
    time(&now);
    return difftime(now, timeout_time);
}

void do_it(int sec)
{
    time_t timeout_time;
    double diff;

    time(&timeout_time);
    timeout_time += sec; /* this is not necessarily correct */

    diff = get_delta_time_to_now(timeout_time);
    while (diff <= 0.0)
    {
        /* do your stuff */

        diff = get_delta_time_to_now(timeout_time);
    }
}

Upvotes: 1

Related Questions