スレッド (thread)

スレッド
順次処理される一連のプログラム。プログラムの最小の実行単位

スレッドの作成

スレッドの作成にはCreateThread APIが用意されていますが、これはマルチスレッドを考慮していないため_beginthread()を利用します。

uintptr_t _beginthread( // NATIVE CODE
  void( __cdecl *start_address )( void * ), //
  unsigned stack_size,                      //
  void *arglist                             //
  );
uintptr_t _beginthreadex( // NATIVE CODE
  void *security,
  unsigned stack_size,
  unsigned ( __stdcall *start_address )( void * ),
  void *arglist,
  unsigned initflag,
  unsigned *thrdaddr
  );
_beginthread、_beginthreadex | MSDN

CreateThread()

HANDLE CreateThread(
  LPSECURITY_ATTRIBUTES lpThreadAttributes, // セキュリティ記述子
  DWORD dwStackSize,                        // 初期のスタックサイズ
  LPTHREAD_START_ROUTINE lpStartAddress,    // スレッドの機能
  LPVOID lpParameter,                       // スレッドの引数
  DWORD dwCreationFlags,                    // 作成オプション
  LPDWORD lpThreadId                        // スレッド識別子
  );
CreateThread 関数 | MSDN

スレッドの終了

_endthread()を呼び出します。

void _endthread( void );
void _endthreadex( unsigned retval );
_endthread、_endthreadex | MSDN

複数スレッドの同期

クリティカル セクション (Critical Section)

クリティカル セクションとは、1つのプロセスに含まれる複数のスレッドが、共有リソースにアクセスするときに排他制御するための仕組みです。

機能 関数 備考
初期化 InitializeCriticalSection()  
所有権獲得 EnterCriticalSection() 所有権が獲得されるまで処理が返されない
TryEnterCriticalSection() すぐに処理が返される
所有権解放 LeaveCriticalSection()  
削除 DeleteCriticalSection()  

これは次のように利用できます。

CRITICAL_SECTION c;

void Func()
{
    EnterCriticalSection(&c);

    // 危険な処理

    LeaveCriticalSection(&c);
}

void Main()
{
    InitializeCriticalSection(&c);

    // 別スレッドからFunc()を呼ぶ

    DeleteCriticalSection(&c);
}

InitializeCriticalSection()

void InitializeCriticalSection(
  LPCRITICAL_SECTION lpCriticalSection
);
InitializeCriticalSection function (synchapi.h) | Microsoft Learn

同期オブジェクト (Synchronization Objects)

型 用途 説明
イベント (Event) 他のスレッドへ通知 Notifies one or more waiting threads that an event has occurred.
ミューテックス (Mutex) リソースの排他制御 Can be owned by only one thread at a time, enabling threads to coordinate mutually exclusive access to a shared resource.
セマフォ (Semaphore) リソースの同時使用数制限 (指定数の排他制御) など Maintains a count between zero and some maximum value, limiting the number of threads that are simultaneously accessing a shared resource.
待機可能タイマー (Waitable timer) タイマーイベントの通知 Notifies one or more waiting threads that a specified time has arrived.
Synchronization Objects - Windows applications | Microsoft Learn

ミューテックス (Mutex)

HANDLE CreateMutexA(
  LPSECURITY_ATTRIBUTES lpMutexAttributes,
  BOOL                  bInitialOwner,
  LPCSTR                lpName
);
CreateMutexA function (synchapi.h) | Microsoft Learn
WaitForSingleObject()

指定のオブジェクトがシグナル状態になるか、タイムアウトするまで待機させられます。

DWORD WaitForSingleObject(
  [in] HANDLE hHandle,       // オブジェクトへのハンドル
  [in] DWORD  dwMilliseconds // タイムアウトの間隔。ミリ秒単位
);
WaitForSingleObject function (synchapi.h) - Win32 apps | Microsoft Learn

hHandleはCreateEvent()で作成でき、それに他のスレッドからSetEvent()でシグナル状態にすることで、このメソッドに状態を伝えられます。

戻り値  
WAIT_OBJECT_0 指定のオブジェクトは、シグナル状態
WAIT_TIMEOUT タイムアウトの時間が経過し、オブジェクトは非シグナル状態
   

複数のオブジェクトを対象とするならば、WaitForMultipleObjects()を用います。

CreateEvent()
HANDLE CreateEventA(
  [in, optional] LPSECURITY_ATTRIBUTES lpEventAttributes,
  [in]           BOOL                  bManualReset,
  [in]           BOOL                  bInitialState,
  [in, optional] LPCSTR                lpName
);
CreateEventA function (synchapi.h) - Win32 apps | Microsoft Learn
SetEvent()
BOOL SetEvent(
  [in] HANDLE hEvent
);
SetEvent function (synchapi.h) - Win32 apps | Microsoft Learn

セマフォ (Semaphore)

ミューテックスとの違いは、ミューテックスでは1つだけの所有権が、セマフォでは複数あることです。

参考

参考書

Microsoft Learnから検索