如何在C++类中安全地使用多线程中的处理函数
1个回答
展开全部
#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <process.h>
typedef unsigned (WINAPI *PBEGINTHREADEX_THREADFUNC)
(LPVOID lpThreadParameter);
typedef unsigned *PBEGINTHREADEX_THREADID;
class ThreadObject
{
public:
ThreadObject();
void StartThread();
void WaitForExit();
static DWORD WINAPI ThreadFunc(LPVOID param);
protected:
virtual DWORD ThreadMemberFunc();
HANDLE m_hThread;
DWORD m_ThreadId;
};
ThreadObject::ThreadObject()
{
m_hThread = NULL;
m_ThreadId = 0;
}
void ThreadObject::StartThread()
{
m_hThread = (HANDLE)_beginthreadex(NULL,0,(PBEGINTHREADEX_THREADFUNC)ThreadObject::ThreadFunc,
(LPVOID)this, 0, (PBEGINTHREADEX_THREADID)&m_ThreadId);
if(m_hThread != NULL)
{
printf("Thread launched\n");
}
}
void ThreadObject::WaitForExit()
{
WaitForSingleObject(m_hThread, INFINITE);
CloseHandle(m_hThread);
}
DWORD WINAPI ThreadObject::ThreadFunc(LPVOID param)
{
ThreadObject* pto = (ThreadObject*)param;
return pto->ThreadMemberFunc();
}
DWORD ThreadObject::ThreadMemberFunc()
{
//std::cout<<"Do Something usefull......."<<endl;
printf("Do Something usefull.......");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//cout<<"hello world!"<<endl;
ThreadObject obj;
obj.StartThread();
obj.WaitForExit();
getchar();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <process.h>
typedef unsigned (WINAPI *PBEGINTHREADEX_THREADFUNC)
(LPVOID lpThreadParameter);
typedef unsigned *PBEGINTHREADEX_THREADID;
class ThreadObject
{
public:
ThreadObject();
void StartThread();
void WaitForExit();
static DWORD WINAPI ThreadFunc(LPVOID param);
protected:
virtual DWORD ThreadMemberFunc();
HANDLE m_hThread;
DWORD m_ThreadId;
};
ThreadObject::ThreadObject()
{
m_hThread = NULL;
m_ThreadId = 0;
}
void ThreadObject::StartThread()
{
m_hThread = (HANDLE)_beginthreadex(NULL,0,(PBEGINTHREADEX_THREADFUNC)ThreadObject::ThreadFunc,
(LPVOID)this, 0, (PBEGINTHREADEX_THREADID)&m_ThreadId);
if(m_hThread != NULL)
{
printf("Thread launched\n");
}
}
void ThreadObject::WaitForExit()
{
WaitForSingleObject(m_hThread, INFINITE);
CloseHandle(m_hThread);
}
DWORD WINAPI ThreadObject::ThreadFunc(LPVOID param)
{
ThreadObject* pto = (ThreadObject*)param;
return pto->ThreadMemberFunc();
}
DWORD ThreadObject::ThreadMemberFunc()
{
//std::cout<<"Do Something usefull......."<<endl;
printf("Do Something usefull.......");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//cout<<"hello world!"<<endl;
ThreadObject obj;
obj.StartThread();
obj.WaitForExit();
getchar();
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询