1、使用_beginthread
#include <windows.h> //sleep
#include <iostream>
#include <process.h> //_beginthread
using namespace std;
class A
{
public:
A()
{
_beginthread(Agent, 0, (void*)this);
}
void run()
{
int i = 0;
while (i++ <10)
{
cout << "Program is running..." << endl;
}
}
private:
static void Agent(void *p)
{
A* a = (A*)p;
a->run();
}
};
int main()
{
A a;
Sleep(2000);
return 1;
}
2、使用CreateThread
#include <windows.h>
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass();
~MyClass()
{ }
void DoSomeThing();
static DWORD WINAPI run(void* param);
private:
HANDLE m_hThread;
};
DWORD MyClass::run(void* param)
{
MyClass* pThis = (MyClass*)param;
pThis->DoSomeThing();
return 0;
}
void MyClass::DoSomeThing()
{
int i = 0;
while (i++<10)
{
cout<<"hello"<<endl;
}
}
MyClass::MyClass()
{
m_hThread = CreateThread(NULL,0,run,(void*)this,0,NULL);
}
int main()
{
MyClass a;
Sleep(2000);
}
3、用模板实现
#include <windows.h>
#include <iostream>
using namespace std;
template <class TYPE, void (TYPE::*RunThread)()>
DWORD WINAPI _thread_t(void* param)
{
TYPE* This = (TYPE*)param;
This->RunThread();
return 0;
}
class MyClass
{
public:
MyClass();
~MyClass()
{
}
void DoSomeThing();
void RunThread();
private:
HANDLE m_hThread;
};
void MyClass::RunThread()
{
this->DoSomeThing();
return;
}
void MyClass::DoSomeThing()
{
int i = 0;
while (i++<10)
{
cout<<"hello"<<endl;
}
}
MyClass::MyClass()
{
m_hThread = CreateThread(NULL,0,_thread_t<MyClass, &MyClass::RunThread>,(void*)this,0,NULL);
}
int main()
{
MyClass a;
Sleep(2000);
}