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;
}

No comments:

Post a Comment