Solaris是怎么支持线程的?超级奇怪的问题.
碰到一极其奇怪的问题.写一极其简单的程序,运行时有两个线程.交替往终端窗口上打印信息.
奇怪的是,程序运行一段时间(时间不定,有时十几分钟,有时2,3个小时)后就停止打印信息了.就好像程序被暂停了一样.
但是奇怪的是程序没有报错,也没有core down.
运行环境:
SUN Ultra 10 + Solaris8 + gcc3.1
各位大侠不妨一试:
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
#include <time.h>
#include <pthread.h>
//time_t -> "2002-12-27 22:57:11"
int t2s(time_t t,char *str)
{
struct tm when;
memcpy(&when,localtime(&t),sizeof(struct tm));
sprintf(str,"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
when.tm_year+1900,
when.tm_mon+1,
when.tm_mday,
when.tm_hour,
when.tm_min,
when.tm_sec);
return 0;
}
pthread_mutex_t mtx;
void log(const char* msg)
{
char buf[256];
time_t t = time(0);
pthread_mutex_lock(&mtx);
t2s(t,buf);
strcat(buf,msg);
printf("%s\n",buf);
pthread_mutex_unlock(&mtx);
}
void * FBThreadProc(void * )
{
try
{
time_t last_reg = 0;
while (1)
{
time_t t = time(0);
if (t - last_reg >= 60)
{
log("处理线程运行中...");
last_reg = t;
}
usleep(1000);
}
}
catch(...)
{
log("工作线程中出现异常...");
}
return NULL;
}
int main()
{
pthread_mutex_init(&mtx,NULL);
try
{
time_t last_reg = 0;
pthread_t m_dThreadID;
if (pthread_create(&m_dThreadID,NULL,FBThreadProc,NULL)!=0)
{
log("create thread failed");
}
while (1)
{
time_t t = time(0);
if (t - last_reg >= 60)
{
log("主线程运行中...");
last_reg = t;
}
usleep(1000);
}
}
catch(...)
{
log("主线程中出现异常...");
}
pthread_mutex_destroy(&mtx);
return 0;
}
g++ ttt.cpp -g -Wall -lpthread -lnsl -I../include -L../source -D_REENTRANT -o ttt