繁体   English   中英

如何从_beginthread线程返回一个值

[英]how to return a value from _beginthread thread

我正在创建一个双线程数组求和程序,我正在使用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];
    }
}

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

int的地址传递给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;
}

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


注意,地址传递给_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. */

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

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

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

如果你改变它

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

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

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

在C ++ 11中,您可能希望将future用于此:

#include <future>
#include <numeric>
#include <iostream>

int arraySum[100];

int partial_sum(int start)
{
    int sum = 0;
    for(int i = start; i < start + 50; ++i)
        sum += arraySum[i];
    return sum;
}

int main()
{
    for(int i = 0 ; i  < 100 ; i++)
    {
        arraySum[i] = i;
    }
    auto a = std::async([]() {return partial_sum(0);});
    auto b = std::async([]() {return partial_sum(50);});
    std::cout << a.get() + b.get() << "\n";
}

也许你想将std::launch::async启动策略传递给std::async来强制创建线程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM