Monday, November 19, 2012

Simple Thread program in c++

//Filename: SimpleThreadTest.cpp
#include <iostream>
#include <windows.h>
#include <process.h>
#include <time.h>

using namespace std;

void myThreadFunction(void *p)
{
  int n = (INT_PTR)p;
  Sleep(n * 1000);
  cout << "Ending Thread At: " << time(NULL) << endl;
}

int main(int argc, const char* argv[])
{
  cout << "Start Time: " << time(NULL) << endl;


  HANDLE myThread = (HANDLE)_beginthread(myThreadFunction, 0, (void*)5);


  WaitForSingleObject(myThread, 100000);
  return 0;
}


______________________________________________________________________________________

//Filename: SimpleMultiThreadTest.cpp

#include <iostream>
#include <windows.h>
#include <process.h>
#include <time.h>

using namespace std;

void myThreadFunction(void *p)
{
  int n = (INT_PTR)p;
  Sleep(n * 1000);
  cout << "Ending Thread At: " << time(NULL) << endl;
}

int main(int argc, const char* argv[])
{
  srand(time(NULL));
  const int threadSize = 5;
  HANDLE myThreads[threadSize];
  for(int i = 0; i < threadSize; i++)
      myThreads[i] = (HANDLE)_beginthread(myThreadFunction, 0, (void*)(rand() % 10 + 1));

  for(int i = 0; i < threadSize; i++)
      WaitForSingleObject(myThreads[i], 100000);
  return 0;
}

No comments:

Post a Comment