Last active
February 22, 2017 07:10
-
-
Save Tocchann/e0d8d5e879aff642ec0a7ccfa41f85b3 to your computer and use it in GitHub Desktop.
マルチスレッドを体感できる簡単なサンプル?
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 <SDKDDKVer.h> | |
#include <Windows.h> | |
#include <process.h> | |
#include <iostream> | |
#include <sstream> | |
#define THREAD_COUNT 10 | |
static unsigned __stdcall ThreadFunc( void* p ); | |
int main() | |
{ | |
HANDLE thrd[THREAD_COUNT]; | |
int setIndex = 0; | |
for( int i = 0 ; i < THREAD_COUNT ; ++i ) | |
{ | |
HANDLE handle = nullptr; | |
//ThreadFunc( IntToPtr( i ) ); // 同期版 | |
handle = reinterpret_cast<HANDLE>( _beginthreadex( nullptr, 0, ThreadFunc, IntToPtr( i ), 0, nullptr ) ); | |
//handle = CreateThread( nullptr, 0, ThreadFunc, IntToPtr( i ), 0, nullptr ); | |
if( handle != nullptr ) | |
{ | |
thrd[setIndex] = handle; | |
std::wstringstream ss; | |
ss << L"Thread launched:" << setIndex << L":" << std::endl; | |
std::wcout << ss.str(); | |
++setIndex; | |
} | |
} | |
WaitForMultipleObjects( setIndex, thrd, TRUE, INFINITE ); | |
for( int i = 0 ; i < setIndex ; ++i ) | |
{ | |
CloseHandle( thrd[i] ); | |
} | |
return 0; | |
} | |
static unsigned __stdcall ThreadFunc( void* p ) | |
{ | |
auto n = PtrToUint( p ); | |
for( int i = 0 ; i < 7 ; ++i ) | |
{ | |
#if 0 | |
// コンソールは共有リソースなので、競合を考える必要がある | |
std::wstringstream ss; | |
ss << n << n << n << n << n << n << n << n << L":" << i << L":" << std::endl; | |
std::wcout << ss.str(); | |
#else | |
std::wcout << L":" << n << n << n << n << n << n << n << n << L":" << std::endl; | |
#endif | |
} | |
std::wstringstream ss; | |
ss << L"Thread exiting:" << n << std::endl; | |
std::wcout << ss.str(); | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
x86/x64 でソースコードを完全共有&スレッド数をちょっと増やしてそれなりスペックマシンでもスレッドコンテキストをより体感できるように変更