gpt4 book ai didi

c++ - 在 C++ 中使用带有指针结构的 beginthread

转载 作者:可可西里 更新时间:2023-11-01 11:52:53 25 4
gpt4 key购买 nike

我正在做一个项目,在这个项目中我必须使用指针结构作为线程的输入参数。我的代码看起来像这样:

struct coord
{
double* xPos;
double* yPos;
};

void cdecl foo( void* inData)
{
coord* my_data = (coord*) inData;

printf("Thread values:\n");
printf("xVal: %f\n", *(my_data->xPos) );
printf("yVal: %f\n", *(my_data->yPos) );
}

主体看起来像这样:

{
double startX = 10;
double startY = 10;
/* declare variables to hold the incoming values */
coord inData;

inData.xPos = &startX;
inData.yPos = &startY;

printf("Initial values:\n");
printf("xVal: %f\n", *(inData.xPos) );
printf("yVal: %f\n", *(inData.yPos) );

_beginthread( foo, 0, (void*) &inData );
}

为什么我的程序显示主线程值不同,我该如何纠正?

最佳答案

您在堆栈上声明您的结构和 double 值,一旦该方法返回(在 _beginthread() 返回之后),堆栈将被删除,导致未定义的行为。

您需要在堆上分配结构,包括double 值。您还需要管理分配的内存。

此外,我不明白您为什么使用 double * 而不是简单地使用 double

编辑:一些示例代码。这会在堆上分配结构并将分配的数据传递回调用者。还有一些工作要做线程同步,这超出了这个问题的范围:

struct coord
{
double xPos;
double yPos;
};

void cdecl foo(void* inData)
{
coord* my_data = (coord*) inData;

printf("Thread values:\n");
printf("xVal: %f\n", my_data->xPos);
printf("yVal: %f\n", my_data->yPos);
}

coord *startThread()
{
coord *inData = new coord;
inData->xPos = 10;
inData->yPos = 10;

_beginthread( foo, 0, (void*) inData );
return inData;
}

int main()
{
coord *data = startThread();
printf("Initial values:\n");
printf("xVal: %f\n", data->xPos);
printf("yVal: %f\n", data->yPos);

// TODO: wait for thread

return 0;
}

关于c++ - 在 C++ 中使用带有指针结构的 beginthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447967/

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