Skip to content

Instantly share code, notes, and snippets.

@kyle-go
Last active December 14, 2015 02:29
Show Gist options
  • Save kyle-go/5013767 to your computer and use it in GitHub Desktop.
Save kyle-go/5013767 to your computer and use it in GitHub Desktop.
sth about windows thread
#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;
}
#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