Wednesday, September 26, 2012

addition of array using _beginthread

This example unlike the previous one, sleeps for a sufficient time until both threads complete their part of the addition.

#include "StdAfx.h"
#include 
#include 
#include 
#include      // needed for _beginthread()

void  partSum( void * );   // function prototype

using namespace std;

#define N 100  

int arraySum[N];

int main()
{
    // Our program's first thread starts in the main() function.

    printf( "Now in the main() function.\n" );

    for(int i = 0 ; i  < 100 ; i++){
        arraySum[i] = i;
    }

    // Let's now create our second thread and ask it to start
    // in the silly() function.
 int result_1 = 1;
    int result_2 = 2;


    _beginthread( partSum, 0, (void*)&result_1 );
    _beginthread( partSum, 0, (void*)&result_2 );

    Sleep( 1000 );

 int fullSum =  result_1 + result_2;
 cout << " fullSum" << fullSum << endl;

    int a;
    cin >> a;

}

void  partSum( void *arg )
{

 int *arg2 = (int*) arg;
    int partialSum = 0;
    for(int i =(N/2) * (*arg2 - 1); i < (N/2) * *arg2 ; i++){
    partialSum += arraySum[i];
    }

    cout << "partialSum" << *arg2 << "= " <<   partialSum << endl;  
 *arg2 = partialSum;
}

addition of array using _beginthreadex WaitForSingleObject

The following code adds all the elements in the array "arraySum" using two threads. This code uses two threads to perform the addition operation and also it uses thread wait call to wait for each of the two threads to exit before they are added by the main thread.

#include "StdAfx.h"
#include <iostream>
#include <windows.h>
#include <process.h>

using namespace std;

#define N 100

int arraySum[N];

unsigned int __stdcall  partSum( void * );   // function prototype

int main()
{

  for(int i = 0 ; i  < N ; i++){
        arraySum[i] = i;
     }

     int  uiThread1ID = 1;
  int  uiThread1ID2 = 2;

     HANDLE  th =  (HANDLE)_beginthreadex(NULL, 0, partSum,(void*)&uiThread1ID, NULL, 0);
  WaitForSingleObject(th, INFINITE/*optional timeout, in ms*/);

  HANDLE  th2 =  (HANDLE)_beginthreadex(NULL, 0, partSum,(void*)&uiThread1ID2, NULL, 0);
  WaitForSingleObject(th2, INFINITE/*optional timeout, in ms*/);

  int fullSum =  uiThread1ID + uiThread1ID2;

  cout << " fullSum" << fullSum << endl;

     int a;
     cin >> a;

    return 0;
}


unsigned int __stdcall  partSum( void *arg )
{
 int *arg2 = (int*) arg;
    int partialSum = 0;
 
    for(int i =(N/2) * (*arg2 - 1); i < (N/2) * *arg2 ; i++){
    partialSum += arraySum[i];
    } 

 cout << "partialSum" << *arg2 << "= " <<   partialSum << endl;
 *arg2 = partialSum;

 return 0;
}