首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从_beginthread线程返回值

如何从_beginthread线程返回值
EN

Stack Overflow用户
提问于 2012-09-26 21:56:29
回答 3查看 3.3K关注 0票数 2

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

代码语言:javascript
复制
#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];
    }
}

我发现很难做到的是让函数将部分和返回给main方法。谁能帮帮我。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-26 21:59:35

int的地址传递给silly(),它可以充当输入和输出参数,并让silly()用调用者所需的值填充它:

代码语言:javascript
复制
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()的变量必须在线程的生命周期内存在。例如,以下情况将导致未定义的行为:

代码语言:javascript
复制
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. */

这可以通过为变量动态分配内存来解决(并确定是主线程还是新线程负责销毁分配的内存)。

票数 6
EN

Stack Overflow用户

发布于 2012-09-26 21:59:24

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

代码语言:javascript
复制
_beginthread( silly, 0, (void*)1 );

如果您将其更改为

代码语言:javascript
复制
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,并可以从那里继续

票数 5
EN

Stack Overflow用户

发布于 2012-09-26 22:26:17

在C++11中,您可能需要使用futures来执行以下操作:

代码语言:javascript
复制
#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::async传递一个std::launch::async启动策略,以强制创建线程。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12603407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档