c++ - 传递给新线程的结构有错误的值

标签 c++ multithreading struct

我需要将多个值传递给新线程(使用 _beginthreadex 函数创建)。我为此创建了一个结构。

struct CaptureThreadInput {
    std::mutex* eventMutex;
    std::condition_variable* eventCv;
    std::vector<DispatchEvent>* eventVector;
    int capId, width, height;
};

我在主线程中使用 Dispatch 对象的私有(private)函数启动了一个新线程。

void Dispatch::startCaptureThread(int i) {
    CaptureThreadInput params = {
        &eventMutex,
        &eventCv,
        &eventVector,
        i, 1280, 720
    };
    CaptureThreadInput* data = &params;
    cout << "Address from dispatch " << std::addressof(*data) << "\n";
    cout << "Mutex from dispatcher " << std::addressof(*(data->eventMutex)) << "\n";
    cout << "CapId from dispatcher " << data->capId << "\n";
    cout << "Width from dispatcher " << data->width << "\n";
    _beginthreadex(NULL, 0, &(CaptureThread::initThread), &params, 0, 0);
}

在启动的线程中,我只调试输出。 CaptureThread::initThread 是一个公共(public)静态函数。

unsigned int __stdcall CaptureThread::initThread(void* in) {
    CaptureThreadInput* data = (CaptureThreadInput*)in;
    cout << "Address from thrd " << std::addressof(*data) << "\n";
    cout << "Mutex from thread " << std::addressof(*(data->eventMutex)) << "\n";
    cout << "CapId from thread " << data->capId << "\n";
    cout << "Width from thread " << data->width << "\n";
    return 0;
}

不过,我从 Dispatch::startCaptureThread 和新创建的线程中创建的结构中获得了不同的值。 Struct 在两个线程中的每一个中返回不同的地址。控制台输出:

Address from dispatch 0000001A83EFF568
Mutex from dispatcher 0000001A83EFFD10
CapId from dispatcher 0
Width from dispatcher 1280
Address from thrd 0000001A83EFF568
Mutex from thread CCCCCCCCCCCCCCCC
CapId from thread -858993460
Width from thread -858993460

我还尝试注释掉 eventMutexeventCveventVector,只留下结构中的整数,结果是一样的。

知道是什么原因造成的吗?我该如何更改我的代码来修复它?

使用适用于 Windows x64 平台的 Microsoft Visual Studio 进行开发。

最佳答案

您在本地创建 params,然后将引用传递给 _beginthreadex,它会立即返回。此时您的 startCaptureThread 退出,导致 params 超出范围。要么防止 params 超出范围,要么按值传递 params

关于c++ - 传递给新线程的结构有错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52128891/

相关文章:

c++ - Directx-局部轴矩阵平移

c++ - 带线程的质数

hadoop - 如何将数据插入 Hive 中的复杂数据类型 "Struct"

c++ - 从 Visual C++ 移植到 Borland C++ Builder 的 ActiveX 代码

c++ - 如何判断一个文件或文件夹是在固态硬盘上还是在硬盘上?

c++ - 线程上下文切换

c# - 为什么 Microsoft 的这段示例代码会崩溃?

c++ - 为什么要将结构包装在匿名 union 中? (STL msvc 实现)

unit-testing - 为什么我们使用接口(interface)来模拟 Golang 方法

c++ - Cmake vs 命令行 : Error in Cmake, 不在命令行