mardi 3 février 2015

Attempting to reference a deleted function when using a mutex

I'm getting a weird error working on a project. I've created a super simple example to recreate the error.


I've created a class. What I'd like to do in this class, is to have a sort of 'getter' function for my class that fills values of a struct. In the main application, the user would instantiate this struct, pass it to a member function, and be able to read the values in the struct upon return. Because of the design of the actual class, this has to happen in a separate thread. Here's what I have:


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;
}


It works as expected. However, because of the asynchronous nature of the class, I need mutexes to protect data being handled in different threads within the class.


If I add a std::mutext as a private member of my class, I receive the following when I try to run the code:


Error 1 error C2280: 'std::mutex::mutex(const std::mutex &)' : attempting to reference a deleted function ...


1) I'm trying to understand why I'm receiving this error.


2) (this part is a little more opinion-based), given the information, is this 'getter' way of filling out a public struct so that someone implementing my class can mess with the variables within it a good design? Is there a better way of doing it?


Aucun commentaire:

Enregistrer un commentaire