开发者

Issue in pausing the posix thread for specific time interval in c

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)


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.


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 ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜