Created
July 29, 2013 14:01
-
-
Save castaneai/6104496 to your computer and use it in GitHub Desktop.
Windowsの超簡単スレッドクラス エラーチェック・同期などはまったく考えていないのでテキトー
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
/* | |
使い方:SimpleThreadのコンストラクタにvoidを返し引数なしの関数を渡すだけ | |
void func() { | |
printf("Hello."); | |
} | |
void main() { | |
SimpleThread t(func); | |
t.Start(); | |
t.Join(); | |
return 0; | |
} | |
*/ | |
#pragma once | |
#include <Windows.h> | |
#include <tchar.h> | |
typedef void (*THREAD_FUNC)(void); | |
class SimpleThread | |
{ | |
public: | |
SimpleThread(THREAD_FUNC threadFunc) | |
: func(nullptr), eventContext(nullptr) | |
{ | |
this->func = threadFunc; | |
this->eventContext = CreateEvent(nullptr, true, false, _T("threadContext")); | |
} | |
void Start() | |
{ | |
QueueUserWorkItem(this->_queueThreadFunc, this, 0); | |
} | |
void Join(int timeoutMilliseconds = INFINITE) | |
{ | |
WaitForSingleObject(this->eventContext, timeoutMilliseconds); | |
} | |
private: | |
THREAD_FUNC func; | |
HANDLE eventContext; | |
static DWORD WINAPI _queueThreadFunc(LPVOID context) | |
{ | |
auto thread = reinterpret_cast<SimpleThread*>(context); | |
thread->func(); | |
SetEvent(thread->eventContext); | |
return 0; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment