Solaris是怎么支持线程的?超级奇怪的问题.

millet 2003-04-20 08:58:36
碰到一极其奇怪的问题.写一极其简单的程序,运行时有两个线程.交替往终端窗口上打印信息.
奇怪的是,程序运行一段时间(时间不定,有时十几分钟,有时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
...全文
40 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zolas 2003-05-11
  • 打赏
  • 举报
回复
顺便检查检查time系列函数是不是线程安全的。有的UNIX操作系统time有专门的线程安全函数,后面多一个_r。
GIShell 2003-05-09
  • 打赏
  • 举报
回复
程序应该还在运行当中,你在
if (t - last_reg >= 60)
{
log("处理线程运行中...");
last_reg = t;
}
中加个else在试试!

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧