Created
January 30, 2015 23:54
-
-
Save Lunaphied/a26d7a94e83e65330f0c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ThreadSample.cpp : Defines the entry point for the console application. | |
// | |
#include "stdafx.h" | |
#include <Windows.h> | |
#include <iostream> | |
#include <list> | |
using namespace std; | |
#define SAFE_DELETE(x) do { if ((x) != NULL) { delete (x); (x) = NULL; }} while(0); | |
typedef struct __TBodyData { | |
std::list<string>* m_pData; | |
} TBodyData, *PTBodyData; | |
class ThreadBody { | |
public: | |
ThreadBody() { | |
} | |
~ThreadBody() { | |
} | |
bool Initialize(void); | |
int Run(void); | |
static DWORD WINAPI ThreadStaticEntryPoint(LPVOID lpData) | |
{ | |
ThreadBody* pThread = (ThreadBody*) lpData; | |
pThread->ThreadEntryPoint(lpData); | |
return 1; | |
} | |
void ThreadEntryPoint(LPVOID lpData) | |
{ | |
// this is where we run the JobTBody | |
if (Initialize() ) | |
Run(); | |
} | |
bool m_bInitialized; | |
TBodyData m_data; | |
}; | |
bool | |
ThreadBody::Initialize(void) { | |
// TODO | |
return true; | |
} | |
int | |
ThreadBody::Run(void) { | |
// Where the loop (that runs until the thread is DONE) is | |
bool condition = true; | |
bool exitcondition = false; | |
while( condition ) { | |
Sleep(20); | |
std::cout << "Sleeping in thread." << std::endl; | |
} | |
return exitcondition; | |
} | |
typedef struct _fakeData { | |
unsigned char data[128]; | |
} FakeData; | |
#define MAX_TH 10 | |
HANDLE hThreadList[MAX_TH]; | |
DWORD dwThreadIdList[MAX_TH]; | |
PTBodyData pDataArray[MAX_TH]; | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
int numberOfThreads = 0; | |
std::list<string> *pData = new std::list<string>(); | |
ThreadBody* pBody = new ThreadBody(); | |
// now if you want to pass data INTO the thread upon creation, here's how: | |
// First allocate an object of the type that would hold the data. | |
pDataArray[numberOfThreads] = (PTBodyData) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(TBodyData)); | |
pDataArray[numberOfThreads]->m_pData = pData; | |
hThreadList[numberOfThreads] = CreateThread(NULL, 0, | |
pBody->ThreadStaticEntryPoint, | |
pDataArray[numberOfThreads], 0, &dwThreadIdList[numberOfThreads]); | |
// When the thread is created, the entry point is fired. That will start the thread. | |
// wait for all threads to finish: | |
for(int i = 0; i < numberOfThreads; i++) { | |
CloseHandle(hThreadList[i]); | |
if (pDataArray[i] != NULL ) { | |
HeapFree(GetProcessHeap(), 0, pDataArray[i]); | |
pDataArray[i] = NULL; // ensure address is NOT reused. | |
} | |
} | |
SAFE_DELETE(pBody); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment