如何从_beginthread线程返回一个值

cro*_*wso 2 c++ multithreading

我正在创建一个双线程数组求和程序,我正在使用windows.h线程.这是我到目前为止的代码.

#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];
    }
}
Run Code Online (Sandbox Code Playgroud)

我似乎很难做到的是让函数将partion sum返回给main方法.请有人帮帮我.

hmj*_*mjd 6

传递一个intto 的地址silly(),它可以作为输入和输出参数,并silly()使用调用者所需的值填充它:

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;
}
Run Code Online (Sandbox Code Playgroud)

您需要等待两个线程完成.


注意,传递地址的变量必须_beginthread()在线程的生命周期内存在.例如,以下将导致未定义的行为:

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. */
Run Code Online (Sandbox Code Playgroud)

这可以通过为变量动态分配内存来解决(并确定主线程或新线程是否可用于销毁已分配的内存).


Sin*_*rMJ 5

你不能让线程本身返回一些东西.相反,您可以在起始调用中使用结构.

_beginthread( silly, 0, (void*)1 );
Run Code Online (Sandbox Code Playgroud)

如果你改变它

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

dataStruct thread_1;
thread_1.ID = 1;
thread_1.returnValue = 0;
_beginthread( silly, 0, (void*)&thread_1 );
Run Code Online (Sandbox Code Playgroud)

然后在你的线程中根据需要设置returnValue,并可以从那里开始