Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a value from _beginthread thread

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.

like image 613
crowso Avatar asked Dec 01 '25 15:12

crowso


2 Answers

Pass the address of an int to silly(), which can act as both input and output parameter, and have silly() populate it with the value required by the caller:

int silly_result_1 = 1;
int silly_result_2 = 2;

_beginthread( silly, 0, (void*)&silly_result_1 );
_beginthread( silly, 0, (void*)&silly_result_2 );

void silly( void *a_arg )
{
    int* arg = (int*) a_arg;
}

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:

void _start_my_thread()
{
    int silly_result = 2;
    _beginthread( silly, 0, (void*)&silly_result );
} /* 'silly_result' is out of scope but still used by the thread. */

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).

like image 97
hmjd Avatar answered Dec 03 '25 04:12

hmjd


You cannot make the thread itself return something. Instead you can use a struct in your starting call.

_beginthread( silly, 0, (void*)1 );

If you change that to

typedef struct dataStruct {
    int ID;
    int returnValue;
};

dataStruct thread_1;
thread_1.ID = 1;
thread_1.returnValue = 0;
_beginthread( silly, 0, (void*)&thread_1 );

Inside your thread you then set the returnValue as needed, and can go on from there

like image 44
SinisterMJ Avatar answered Dec 03 '25 05:12

SinisterMJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!