正文 在VC下,MFC console程序默认行为是单线程工作环境。我们可以用下面二种方法将其工作环境中的单线程改为多线程。
1、在“工程->设置->C/C++”下的Code Generation选项中,将Use run-time library设为Multithreaded(多线程)。
2、可以在当前的Project Options 中加入“/MT”。(表示使用多线程版本的C runtime函数库)
#include <stdio.h>
#include <afx.h>
#include <fstream>
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;
}
需载入所使用类的头文件(AFX.h),这样就可以使用与GUI无关的MFC类,本例中使用的是CString。