【发布时间】:2016-06-13 10:07:34
【问题描述】:
大家晚上好!
我正在尝试使用 Microsoft Visual Studio Express 2012 在 C++ 中编写多线程应用程序。
我们的想法是“main”函数调用一个将“永远”运行的线程,其任务是更新对象。
这是主要的:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <thread>
#include <iostream>//debug only
#include <fstream> //debug only
#include "dataCollectorFTL.h"
int _tmain(int argc, _TCHAR* argv[])
{
dataCollectorFTL dataCollector1;
//Launch thread which will run forever and get the data flows
dataCollector1.runDataCollector();
while(true){
//application running
}
return 0;
}
这是类的“.h”
#ifndef DATACOLLECTORFTL_H_INCLUDED
#define DATACOLLECTORFTL_H_INCLUDED
#include <thread>
class dataCollectorFTL {
public:
void runDataCollector();
void getData();
//constructor, destructor
dataCollectorFTL();
~dataCollectorFTL();
private:
HANDLE hProcess;
std::thread dataCollectorThread;
};
#endif // DATACOLLECTORFTL_H_INCLUDED
最后是“.cpp”
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <thread>
#include "dataCollectorFTL.h"
void dataCollectorFTL::runDataCollector(){
//lauch a non-local thread
dataCollectorThread = std::thread(&dataCollectorFTL::getData, this);
}
void dataCollectorFTL::getData(){
//some stuff
}
dataCollectorFTL::dataCollectorFTL(){
//some stuff
}
dataCollectorFTL::~dataCollectorFTL(){
dataCollectorThread.join();
}
问题是当我运行它时,它给了我这两个错误:
错误 1 错误 C2248:“std::thread::operator =”:无法访问在类“std::thread”c:\users\damien\documents\visual studio 2012\projects\recherche\recherche 中声明的私有成员\datacollectorftl.h 233 1 研究
错误 4 错误 C2248:“std::thread::thread”:无法访问在类“std::thread”c:\users\damien\documents\visual studio 2012\projects\recherche\recherche\ 中声明的私有成员datacollectorftl.h 233 1 研究
为了节省时间,我可以告诉你:
- 包含在 .h 中不会改变任何内容
- runDataCollector 方法的内容不会改变任何东西。即使它是空的,我仍然遇到问题
- std::thread dataCollectorThread 可以是公共的也可以是私有的,它不会改变任何东西
如果我不声明为类的成员,我的程序就会崩溃,因为我没有 join() runDataCollector() 中的线程。我不想加入它,getData() 是一个 while(true) 函数,它从另一个软件获取数据。
非常感谢您花时间阅读本文,再次感谢您的帮助。
【问题讨论】:
-
您正试图在某处复制分配
dataCollectorFTL。当然不是在您发布的代码中。 -
两个错误都突出显示
datacollectorftl.h中的第 233 行。你能把确切的行贴出来吗?您很难看出编译器在哪里抱怨。 -
呈现的代码看起来不错; coliru.stacked-crooked.com/a/2c1af3a84792c771。您确定您没有在某处复制父级
dataCollectorFTL类,这会导致您看到的错误。将其复制和赋值运算符设为私有,错误消息将有助于诊断副本的位置。如果没有,minimal reproducible example 会有所帮助。 -
感谢大家的帮助。不幸的是,John Burger 的帮助并没有解决问题。恐怕不能完全理解什么是复制分配。第 233 行是 .h 中类的结尾。就代码而言,它是'};'我会给你完整的代码。然而它有点乱,为了早期测试我没有把任何东西保密。请原谅这么糟糕的编码。
标签: c++ multithreading visual-studio-express