传递给新线程的结构的值错误

时间:2018-09-01 14:09:51

标签: c++ multithreading struct

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

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

我使用主线程中Dispatch对象的私有功能启动了一个新线程。

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是公共静态函数。

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,只在结构中保留整数,结果是相同的。

有什么想法会导致这种情况,如何更改代码以解决此问题?

使用Microsoft Visual Studio for Windows x64平台进行开发。

1 个答案:

答案 0 :(得分:3)

您正在本地创建memory_profiler,然后将引用传递到params中,该引用立即返回。此时,您的_beginthreadex退出,导致startCaptureThread超出范围。阻止params超出范围,或按值传递params