Last active
December 14, 2015 02:29
-
-
Save kyle-go/5013767 to your computer and use it in GitHub Desktop.
sth about windows thread
This file contains 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
#include "thread.h" | |
#include <memory> | |
int main() | |
{ | |
struct UR_STRUCT | |
{ | |
int a; | |
//... | |
}; | |
std::shared_ptr <UR_STRUCT> ptr(new UR_STRUCT); | |
ptr->a = 100; | |
std::function<void(std::shared_ptr<UR_STRUCT>)> func = [](std::shared_ptr<UR_STRUCT> ptr){ | |
//do some thing with ptr... | |
}; | |
thread::newThread(true, std::bind(func, ptr)); | |
return 0; | |
} |
This file contains 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
#ifndef _THREAD_H | |
#define _THREAD_H | |
#include <functional> | |
#include <windows.h> | |
namespace thread | |
{ | |
typedef std::tr1::function<void(void)> xfunction; | |
DWORD __stdcall ApiThread(void * param) { | |
(*static_cast<xfunction*>(param))(); | |
delete static_cast<xfunction*>(param); | |
return 0; | |
} | |
bool newThread(bool bWait, xfunction func) { | |
if (func._Empty()) | |
return false; | |
xfunction * pfunc = new xfunction; | |
if (!pfunc) | |
{ | |
return false; | |
} | |
*pfunc = func; | |
HANDLE hthread = CreateThread( | |
NULL, | |
NULL, | |
ApiThread, | |
(void *)pfunc, | |
NULL, | |
NULL); | |
if (!hthread) | |
{ | |
delete pfunc; | |
return false; | |
} | |
if (bWait) | |
WaitForSingleObject(hthread, INFINITE); | |
CloseHandle(hthread); | |
return true; | |
} | |
} | |
#endif //_THREAD_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment