I am in the process of creating a two thread array summation program and i am using windows.h threads. And this is the code that i have so far.
#include "StdAfx.h"
#include <stdio.h>
#include <iostream>
#include <windows.h>
#include <process.h> // needed for _beginthread()
void silly( void * ); // function prototype
using namespace std;
int arraySum[100];
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.
_beginthread( silly, 0, (void*)1 );
_beginthread( silly, 0, (void*)2 );
Sleep( 100 );
int a;
cin >> a;
}
void silly( void *arg )
{
printf( "The silly() function was passed %d\n", (INT_PTR)arg ) ;
int partialSum = 0;
for(int i =50*((INT_PTR)arg - 1); i < 50 * ((INT_PTR)arg) ; i++){
partialSum == arraySum[i];
}
}
What i seem to find it hard to do is make the function return the partion sum to the main method. Could someone please help me out.
Pass the address of an
inttosilly(), which can act as both input and output parameter, and havesilly()populate it with the value required by the caller:You need to wait for the two threads to complete.
Note it is necessary that the variables whose addresses are passed to
_beginthread()exist for the lifetime of the thread. For example, the following would result in undefined behaviour:This can be solved by dynamically allocating memory for the variable (and decide whether the main thread or the new thread is reponsible for destroying the allocated memory).