Skip to content

Instantly share code, notes, and snippets.

@Tocchann
Last active February 22, 2017 07:10
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 Tocchann/e0d8d5e879aff642ec0a7ccfa41f85b3 to your computer and use it in GitHub Desktop.
Save Tocchann/e0d8d5e879aff642ec0a7ccfa41f85b3 to your computer and use it in GitHub Desktop.
マルチスレッドを体感できる簡単なサンプル?
#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;
}
@Tocchann
Copy link
Author

x86/x64 でソースコードを完全共有&スレッド数をちょっと増やしてそれなりスペックマシンでもスレッドコンテキストをより体感できるように変更

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment