A thread is started by a member function

Source: Internet
Author: User

/*shows How to start a thread based on a
Class Memeber function using a static member function.*/


#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;
/*this Threadobject is created by a
Thread that wants to start another thread.
All public member functions except ThreadFunc ()
is called by that original thread. The virtual function
Threadmemberfunc () is the start OG the new thread.
*/
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)
printf ("Thread lauched\n");
}
void Threadobject::waitforexit ()
{
WaitForSingleObject (M_hthread, INFINITE);
CloseHandle (M_hthread);
}
Static member functions has no "this" pointer;
DWORD WINAPI threadobject::threadfunc (LPVOID param)
{
Use the Param as the address of the object
Threadobject *pto = (threadobject*) param;
return Pto->threadmemberfunc ();
}


DWORD Threadobject::threadmemberfunc ()
{
Do something useful ...
return 0;
}
void Main ()
{
Threadobject obj;
Obj. Startthread ();
Obj. WaitForExit ();
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

A thread is started by a member function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.