Skip to content

Instantly share code, notes, and snippets.

@castaneai
Last active December 20, 2015 08:59
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/6104314 to your computer and use it in GitHub Desktop.
Save castaneai/6104314 to your computer and use it in GitHub Desktop.
Windowsで簡単なスレッドの使用例
/*
5秒カウントダウンして終了するだけの簡単なスレッドのサンプル
*/
#include <iostream>
#include <Windows.h>
// 引数でスレッドの終了を伝えるためのイベントハンドルを受け取る
DWORD WINAPI func(LPVOID eventContext)
{
// 5秒カウントダウンする
for (int i = 5; i > 0; i--) {
Sleep(1000);
std::cout << i << std::endl;
}
// スレッドが終了したことをイベントを使って伝える
SetEvent(reinterpret_cast<HANDLE>(eventContext));
// スレッドの関数は正常終了したら0を返す必要がある
return 0;
}
int main(void)
{
// スレッドの終了を伝えるためのイベントハンドルを作る
auto eventContext = CreateEvent(nullptr, true, false, L"ThreadTerminationEvent");
// funcを別スレッドで実行する
QueueUserWorkItem(func, eventContext, 0);
// イベントハンドルを使ってスレッドの終了を待つ
WaitForSingleObject(eventContext, INFINITE);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment