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

标签 c++ windows multithreading pointers structure

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

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/

相关文章:

c++ - Ubuntu 或 Windows 中的代码块。有什么不同吗?

c++ - 在 PocketPC 上运行后台服务

c++ - 如何在 Xcode 6.1.1 中使用 google test 运行本地 c++ 单元测试

java - 我应该在 Android 中使用 AsyncTask 来管理套接字连接吗?

c++ - 在不损失性能的情况下提高代码可读性

python - 在 Windows 上安装 PyUblas

windows - 在 Windows 上使用 htaccess 文件 - 实际上将文件另存为 .htaccess?

mysql - 如何从 windows 命令提示符连接到 mysql 命令行

node.js - 如何在 Node.js 中的两个工作线程之间创建直接通信 channel

multithreading - 在pthread中,如何可靠地将信号传递给另一个线程?