Linux多核心服务器time函数bug

最近开发一个模块用到了多线程,也用到了Linux下的时间函数

结果发现一个bug,多核心服务器下time函数会突然出现返回比正常时间多4000多秒的情况

我们用的Linux操作系统是Red Hat Enterprise Linux 5.0,内核版本2.6.18-8.el5

以下是测试程序

#include <iostream>
#include <pthread.h>
#include <time.h>
using namespace std;
void *thr1_fun(void* param)
{
time_t now, pre;
time(&pre);
time(&now);
for (;;)
{
if(time(&now) == -1)
perror("time");
if ((now - pre) >  5)
{
std::cout << "thr1_fun  " << "  now-pre " << now-pre << std::endl;
pre = now;
}
}
}
void *thr2_fun(void* param)
{
time_t now, pre;
time(&pre);
time(&now);
for (;;)
{
if(time(&now) == -1)
perror("time");
if ((now - pre) > 5)
{
std::cout << "thr2_fun  " << "  now-pre " << now-pre << std::endl;
pre = now;
}
}
}
int main()
{
pthread_t th1,th2;
pthread_create(&th1, NULL, thr1_fun, NULL);
pthread_create(&th2, NULL, thr2_fun, NULL);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
return 0;
}

2个线程不停的运行time函数得到当前时间,运行结果偶尔一个线程 now-pre会打印出4000多的数值,并且并未发现time函数执行失败,然后那个打印出4000多数值的线程就死掉了。

查了一下资料,这个好像是内核的一个bug。

在Ubuntu 10.04,内核版本2.6.32上测试,没有这个bug。

相关推荐