concole程序,先在setting--C/C++--Code Generation---use runtime Lib中改一下 // thread.h: interface for the thread class. #include "windows.h" #include <process.h> class thread { public: int Get(); void Add(); void Stop(); void Start(); thread(); virtual ~thread(); private: static void __cdecl ThreadProcess( LPVOID pParam ); //member private: int m_nint; HANDLE m_hExit; // HANDLE m_hAccess; HANDLE m_hThread; }; // thread.cpp: implementation of the thread class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "thread.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// thread::thread() { m_hExit=CreateEvent(NULL,FALSE,FALSE,NULL);//初始化事件:1.安全信息,2.自动重置,3.初始值为无响应,4.无名称 m_nint=0; } thread::~thread() { Stop(); CloseHandle(m_hExit); // CloseHandle(m_hAccess); } void thread::Start() { m_hThread=(HANDLE)_beginthread(ThreadProcess,0,this); } void thread::Stop() { SetEvent(m_hExit); WaitForSingleObject(m_hThread,INFINITE);//无限制等待线程结束,当然也可以设定较小的超时值。 } void __cdecl thread::ThreadProcess( LPVOID pParam ) { thread* pThread=(thread*)pParam; HANDLE hExit=pThread->m_hExit; while(1) { //提前结束线程:将等待时间设为0,函数将只检查事件是否有信号,如果有信号返回WAIT_OBJECT_0 if(WAIT_OBJECT_0==WaitForSingleObject(hExit,0)) return ; //这里可访问类的成员和方法 //建议全部访问利用同步对象保护的方法来存取对象(int等较小数据结构可以不保护) pThread->Add(); } } void thread::Add() { if(m_nint>100000)m_nint=0; m_nint++; } int thread::Get() { return m_nint; } //由于MFC类很多不是线程安全的(特别是界面有关的),将MFC指针传递进去可能会运行出错。