NtKinect: Kinect V2 C++ Programming with OpenCV on Windows10

How to run Kinect V2 in a multi-thread environment


2016.08.24: created by
Japanese English
This article is for NtKinect.h version 1.6 or later
To Table of Contents

Prerequisite knowledge


Multi-thread Programming on Windows

NtKinect

To write a program that runs in multi-threading on Windows, first include "proces.h".

#include <process.h>

The function unsigned func (LPVOID) runs in the thread is defined in the following format.

unsigned __stdcall func (LPVOID pParam) {

  // The work this thread should do.

  _endthreadex(0);
  return 0;
}

For programs that operate in multi-threading, exclusive control must be needed in critical sections where conflicts may occur. We use Mutex for this purpose. We create a mutex as a variable that can be refered from any thread, and we decide that only the thread that acquire the right of the mutex can enter the critical section.

Handle mutex;

int main(int argc, char** argv) {
  mutex = CreateMutex(NULL, FALSE, NULL); // create mutex
  if (GetLastError() == ERROR_ALREADY_EXISTS) throw ERROR;

  ...(abbreviated)...

}

unsigned __stdcall func (LPVOID pParam) {

  ...(abbreviated)...

  DWORD ret = WaitForSingleObject(mutex, INFINITE); // acquire the right of Mutex
  if (ret == WAIT_FAILED) throw ERROR;

  ...(abbreviated)... // critical section

  ReleaseMutex(mutex); // release the right of Mutex

  ...(abbreviated)...

  _endthreadex(0);
  return 0;
}

To start N threads in the main thead, write as follows. _beginthreadex() function is used to start a thread, and WaitForMultipleObjects() function is used to wait for all threads to finish.

  HANDLE hThread[N ] = { 0 };

  hThread[0] = (HANDLE) _beginthreadex(NULL,0, functionName1,NULL,0,NULL); // create thread to call function1
  if (hThread[0] == 0) throw Error ;

  ...(abbreviated)... // create threads of 2〜(N-2)

  hThread[N -1] = (HANDLE) _beginthreadex(NULL,0,functionName>N,NULL,0,NULL); // create thread to call functionN
  if (hThread[N -1] == 0) throw Error ;

  ...(abbreviated)... // Job for the main thread

  DWORD ret = WaitForMultipleObjects(N ,hThread,TRUE,INFINITE); // wait for all threads to finish
  if (ret == WAIT_FAILED) throw Error ;
  return 0;
}

If you define USE_THREAD constant before including NtKinect.h, the functions and variables of NtKinect for multi-thread become effective.