如何在C++类中安全地使用多线程中的处理函数

 我来答
好程序员
2016-12-08 · HTML5前端培训/大数据培训/Java
好程序员
好程序员是IT高端课程培训基地,从平凡到卓越,为梦想而拼搏。
向TA提问
展开全部
#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;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式