我必须在单独的线程中调用一个方法(我使用的是posix线程),它在每5秒后更新一些值,并编写了下面的代码。
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);但是这个线程在4-5分钟后出现分段错误,这可能是.What的原因?有没有其他方法可以暂停POSIX线程。(我使用linux)
发布于 2010-08-20 19:53:35
正确的做法是使用纳米睡眠,因为我们的睡眠和睡眠可能会扰乱SIGALARM,而纳米睡眠是专门为线程而设计的:
struct timespec mytimeout = {
.tv_sec = 5,
.tv_usec = 0,
};
struct timespec remaining;
nanosleep(&mytimeout, &remaining);我最初的回答是使用select技巧,但让我们停止推广糟糕的代码
回到问题的根源,你怎么知道你的分割错误来自休眠代码?你得到了一个可以回溯的核心转储吗?
发布于 2010-08-20 20:27:41
在POSIX系统( linux就是)上,nanosleep是这种睡眠的最佳选择:
int nanosleep(const struct timespec *req, struct timespec *rem);其中req是您的请求,rem是线程过早中断时剩余的休眠时间。
https://stackoverflow.com/questions/3529337
复制相似问题