我在做一个项目时遇到了奇怪的错误。我创建了一个超级简单的示例来重现这个错误。
我创建了一个类。在这个类中,我希望有一种“getter”函数可以填充一个struct
的值。在主应用程序中,用户会实例化这个struct
,将其传递给一个成员函数,并能够在返回时读取struct
中的值。由于实际类的设计,这必须在一个单独的线程中进行。这是我的代码:
myClass.h:
#ifndef __MY_CLASS_H__
#define __MY_CLASS_H__
#include <mutex>
class myClass {
public:
struct my_struct_s {
int field1;
short field2;
};
int get_data(my_struct_s & my_struct);
private:
};
#endif /* __MY_CLASS_H__ */
myClass.cpp:
#include "myClass.h"
int myClass::get_data(struct my_struct_s & my_struct)
{
int var1 = 5;
char var2 = 2;
my_struct.field1 = var1;
my_struct.field2 = var2;
return 0;
}
Main.cpp:
#include "myClass.h"
#include <iostream>
#include <thread>
#include <Windows.h>
bool thread_running;
std::thread thread;
void run_thread(myClass & lmyClass)
{
myClass::my_struct_s my_struct;
while (thread_running) {
lmyClass.get_data(my_struct);
std::cout << my_struct.field1 << std::endl;
std::cout << my_struct.field2 << std::endl;
Sleep(100);
}
}
int main(int argc, char *argv[])
{
myClass lmyClass;
thread_running = true;
thread = std::thread(run_thread, lmyClass);
Sleep(1000);
thread_running = false;
if (thread.joinable()) {
thread.join();
}
getchar();
return 0;
}
它的表现如预期。但是,由于该类的异步性质,我需要使用互斥锁来保护在类内不同线程中处理的数据。
如果我将std::mutex
作为我的类的私有成员添加进去,在尝试运行代码时会收到以下错误:
Error 1 error C2280: 'std::mutex::mutex(const std::mutex &)' : attempting to reference a deleted function ...
1) 我正在尝试理解为什么会出现此错误。
2) (这部分有点基于意见)考虑到以上信息,通过一种'getter'的方式填充公共结构体以便实现我的类可以操纵其中的变量,是否是一个好的设计?还有更好的方法吗?
std::mutex
时出现问题的实际代码。 - Remy Lebeaustart()
、stop()
、set_mode()
这样的公共成员,这些成员会通过串口发送消息,但是读取线程永远不会停止。它只是在知道响应帧后处理响应帧。一旦帧被识别,它们就被放入队列中,这就是我想让我的“getter”函数从中提取数据的地方。这就需要互斥锁,显然(异步队列访问)。 - justynnuff