Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created July 29, 2013 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save castaneai/6104496 to your computer and use it in GitHub Desktop.
Save castaneai/6104496 to your computer and use it in GitHub Desktop.
Windowsの超簡単スレッドクラス エラーチェック・同期などはまったく考えていないのでテキトー
/*
使い方: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