Windows Threading Techniques in C++


Threading can be created by the following 3 methods 
1- _beginthread
2- _beginthreadex
3- createthread

The following examples  were written using Borland C++ 5.02

_beginthread(Function Name , Stack Size , Parameter To Pass)

#include <process.h>

void ThreadProc(void *param);
int main()
{
  int n, i;
  int val = 0;
  HANDLE handle;
  printf("Enter the number of threads : ");
  scanf("%d",&n);

  for(i=0;i<n;i++)
  {
  val = i+1;
  handle = (HANDLE) _beginthread( ThreadProc,0,&val);
  WaitForSingleObject(handle,INFINITE);
  }
  cin.get();
}

void ThreadProc(void *param)
{
  int h=*((int*)param);
  printf("%d Thread is Running!\n",h);
  _endthread();
} 
 

Capturing the Error Code of A Thread GetExitCodeThread
#include <windows.h>
#include <stdio.h>
#include <process.h>

void Thread1(void *p);

int main()
{
    HANDLE  Thread;
    LPDWORD lpExitCode; 
    int code;
    Thread = (HANDLE) _beginthread(Thread1,0,0);
    Sleep(4000);
    GetExitCodeThread(Thread,lpExitCode);
    cout <<  "Start---"<<  lpExitCode <<"----End" ;
    code = int(*lpExitCode);
   
     if (code == 259)
     {
     cout << "Thread has endded";
     }
    cout << "This should show up" ;
    CloseHandle(Thread);
}


void Thread1(void *p)
{
      int i = 0;
      while(1)
      {
               printf("%u ", i);
               i = rand();
               Sleep(500);
      }
      cout << "Finished" << "\n";
}

No comments:

Post a Comment