一个控制台程序中的日志产生程序(运用多线程)

      正文    在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。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值