MenüHomeBlogMagic

Windows C/C++ einfaches CreateThread Beispiel

Hier ein einfaches Beispiel um in Windows einen Thread zu kreieren.

#include <stdio.h>
#include <windows.h>

bool g_bThreadDone;

DWORD WINAPI threadFunction(void *pParam)
{
  int* piSampleParam = static_cast<int*>(pParam);
  printf("Thread started with param: %d\n", *piSampleParam);
  g_bThreadDone = true;
  return 0;
}

int main(int iArgc, char** ppcArgv)
{
  int iReturn = 0;
  g_bThreadDone = false;
  DWORD uiThredId;
  int iSampleParam = 100;
  HANDLE hThread = CreateThread(0, 0, threadFunction, &iSampleParam, 0, &uiThredId);
  if (hThread != NULL)
  {
    while (g_bThreadDone == false)
    {
      printf("Waiting for thread done\n");
      // Give thread time to run!
      Sleep(100);
    }
    printf("Thread closed\n");
  }
  else
  {
    iReturn = -1;
    printf("Failed to start thread\n");
  }
  return iReturn;
}