我需要将多个值传递给新线程(使用_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 = ¶ms;
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), ¶ms, 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
我也试着评论eventMutex
,eventCv
和eventVector
只留下结构中的整数,结果是一样的。
知道是什么导致了这个,我怎么能改变我的代码来修复它?
使用Microsoft Visual Studio for Windows x64平台进行开发。
你在本地创建params
,然后将引用传递给_beginthreadex
,它会立即返回。那时你的startCaptureThread
退出,导致params
超出范围。要么阻止params
超出范围,要么通过值传递params