Win32並行処理プログラミング入門33
早速ですが、論よりサンプルプログラムです。
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <process.h>
using namespace std;
//鳥の発言
unsigned __stdcall PiyoFunc( void* pvParam )
{
for ( ; ; ) {
cout << " ピヨ " ;
SwitchToThread();
}
return 0;
}
//猫の発言
unsigned __stdcall NyaFunc( void* pvParam )
{
for ( ; ; ) {
cout << " にゃ〜 ";
SwitchToThread();
}
return 0;
}
//にゃんぴよ会議開催
int _tmain( int, _TCHAR* )
{
const int threadCount = 2;
HANDLE hThreads[ threadCount ];
//ピヨスレッドを作成する
hThreads[ 0 ] = reinterpret_cast< HANDLE >(
_beginthreadex (
__nullptr,
0U,
PiyoFunc,
reinterpret_cast< void * >( ( INT_PTR ) 0 ) ,
CREATE_SUSPENDED, //直ぐには実行しない
__nullptr ) );
//にゃ〜スレッドを作成する
hThreads[ 1 ] = reinterpret_cast< HANDLE >(
_beginthreadex (
__nullptr,
0U,
NyaFunc,
reinterpret_cast< void * >( ( INT_PTR ) 0 ) ,
CREATE_SUSPENDED, //直ぐには実行しない
__nullptr ) );
//強制的に終わらせるためmain関数の優先順位を高くする
SetThreadPriority(
GetCurrentThread(),
THREAD_PRIORITY_TIME_CRITICAL );
//作成したスレッドを実行
for ( int i = 0; i < threadCount; i++) {
ResumeThread( hThreads[ i ] );
}
//タイムアウト時間をミリ単位で指定して待機
//※指定した時間は正確ではありません
DWORD result = WaitForMultipleObjects(
threadCount, hThreads, TRUE, 200 );
//WaitForSingleObject関数が終了した原因を表示
unsigned int max = ( WAIT_OBJECT_0 + threadCount - 1 );
if ( result == WAIT_FAILED ) {
//エラーを表示する
DWORD error = GetLastError();
LPVOID title = _T( "エラー" );
LPVOID msg;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
__nullptr,
GetLastError(),
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // 既定の言語
reinterpret_cast< LPTSTR >( &msg ),
0,
__nullptr
);
MessageBox( __nullptr,
reinterpret_cast< LPCTSTR >( msg ) ,
reinterpret_cast< LPCTSTR >( title ),
MB_OK | MB_ICONERROR );
LocalFree( msg );
return -1;
}
if ( result == WAIT_TIMEOUT ) {
cout << "【時間切れワン。本日の会議は終了するワン。】" << endl;
} else if ( ( result >= WAIT_OBJECT_0 ) & ( result <= max ) ) {
cout << "全スレッドの処理が終わりました。" << endl;
}
cout << endl;
//ハンドルを閉じる
for ( int i = 0; i < threadCount; i++ ) {
CloseHandle( hThreads[ i ] );
hThreads[ i ] = __nullptr;
}
cout << endl;
return 0;
}
<\code>
このサンプルは、猫と鳥が会議している様子を表しています。スレッドのスケジューリングに関する関数を使用しています。ちなみに、進行役は犬が勤めています。次回このサンプルを用いて、Windowsにおけるスレッドのスケジューリングおよび、スレッドスケジューリングに関するWin32APIを解説します。続く...