gpt4 book ai didi

c++ - 如何从 _beginthread 线程返回一个值

转载 作者:太空狗 更新时间:2023-10-29 23:36:44 26 4
gpt4 key购买 nike

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

我觉得很难做的是让函数将分区总和返回给 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. */

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

关于c++ - 如何从 _beginthread 线程返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12603407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com