tags:

views:

45

answers:

2

I have to call one method in seperate thread (i am using posix thread)which updates some value after every 5 second for which have written below code.

void *threadEntry(void *)
{
  while(1)
  {
    updateValue();//to update some values
    usleep(5000000);//pause for 5 second
   }
}
pthread_t thread1;
pthread_create(&thread1,NULL,threadEntry,NULL);

But this thread gets segmentation fault after 4-5 minutes .What can be reason?Is there any other way to pause the posix thread.(i am using linux)

A: 

The right thing to do is to use nanosleep, because usleep and sleep might mess with SIGALARM, while nanosleep was specifically designed with threads in mind :

struct timespec mytimeout = {
    .tv_sec = 5,
    .tv_usec = 0,
};
struct timespec remaining;
nanosleep(&mytimeout, &remaining);

My original answer was to use a select trick, but let's stop promoting bad code

Back to the root of the problem, how do you know your segmentation fault come from the sleeping code ? Did you get a core dump you could backtrace ?

shodanex
Ough, long time that I didn't see that hack. No, don't do that, use `nanosleep`.
Jens Gustedt
You are damn right
shodanex
+1  A: 

On POSIX systems (which linux is) nanosleep is the right thing for such a sleep:

int nanosleep(const struct timespec *req, struct timespec *rem);

where req is your request an rem is the time remaining to sleep if your thread was interrupted prematurely.

Jens Gustedt