分类: C/C++
2008-08-04 09:31:30
class CMyfile { public: CMyfile() { InitializeCriticalSection(&cs); } ~CMyfile() { DeleteCriticalSection(&cs); } void msglog(char* buffer,int length,int wait) { static int i=0; CString a; a.Format("%d#",i ); if (m_bSync) EnterCriticalSection(&cs); fwrite("\n", 1, 1, fstream); fwrite(a CString(''-'',50), 52, 1, fstream); fwrite("\n", 1, 1, fstream); fwrite(buffer, length, 1, fstream); Sleep(wait); fwrite("\n", 1, 1, fstream); fwrite(a CString(''-'',50), 52, 1, fstream); fflush(fstream); if (m_bSync) LeaveCriticalSection(&cs); } bool openfile(CString filename,bool bSync) { m_filename=filename; m_bSync=bSync; if((fstream=fopen(filename, "wt")) == NULL) return false ; else return true; } void closefile() { fclose(fstream); } protected: CRITICAL_SECTION cs; FILE* fstream; CString m_filename; bool m_bSync; private: };
测试代码:
UINT threadFunc( LPVOID p); void CBDlg::OnButton2() { // TODO: Add your control notification handler code here CMyfile file; if (m_sync.GetCheck()==1) file.openfile("1.txt",true);//同步 else file.openfile("1.txt",false);//异步 CWinThread* thd[10]; HANDLE hThd[10]; for(int i=0;i<10;i ) { thd[i]=AfxBeginThread(threadFunc,&file); //故意制造线程启动时间的不一致 Sleep(10); hThd[i]=thd[i]->m_hThread; } //等待所有线程结束 WaitForMultipleObjects(10,hThd,true,INFINITE); file.closefile(); AfxMessageBox("ok"); } UINT threadFunc( LPVOID p) { CMyfile* file=(CMyfile*)p; long lThreadID = ::AfxGetThread()->m_nThreadID; CString a; a.Format("thread %d",lThreadID); for (int i=0;i<100;i ) { CTime time=CTime::GetCurrentTime(); CString str=time.Format("%y-%m-%d %H:%M:%S"); str=str "--------->" a; file->msglog(str.GetBuffer(str.GetLength()),str.GetLength(),lThreadID/100); } return 1; }下载本文示例代码