|
|
一个控制台程序中的日志产生程序(运用多线程) |
|
|
作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站 |
在VC环境下,MFC console程序默认行为是单线程工作环境。我们在“工程->设置->C\C++”下的Code Generation选项中,将Use run-time library设为Multithreaded(多线程)。也可以在当前当前的Project Options 中加入“/MT”。(表示使用多线程版本的C runtime函数库)
#include
#include
#include
using namespace std;
void ReadTime()
{
ofstream f;
CString str;
int iNu = 0;
while(1)
{
CTime ct = CTime::GetCurrentTime();
str.Format("%d年%d月%d日:%d:%d", (int)ct.GetYear(),
(int)ct.GetMonth(), (int)ct.GetDay(),
(int)ct.GetMinute(), (int)ct.GetSecond());
f.open("w.txt", ios::app );
f << (LPCTSTR)str << endl;
str.Format("%d\n", iNu);
printf("%s", str);
Sleep(1000);
iNu++;
f.close();
}
}
int main()
{
HANDLE hThread; // 返回的线程句柄,想早早结束线程,可通过该句柄
DWORD ThreadID;// 记录线程ID号
int iNu;
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadTime,
NULL, 0, &ThreadID);
for (int i=0; i<10000;i++)
for(int j=0; i<10000; j++)
{
Sleep(1000);
}
return 0;
}
对于这个程序我做几点说明:
1:需载入所使用类的头文件(AFX.h),这样就可以使用与GUI无关的MFC类,本例中使用的是CString。
2:本例中我没有用CFile 或者是CStdioFile类,我觉得用ofstream 更简洁,要是你不服气,你可以用CFile试试,看你多写多少代码?

|
|
相关文章:相关软件: |
|