I am trying to get a simple network program to work with threads. The idea was to have two threads, one for sending and one for receiving data over a socket. The thread responsible for reading data would update a buffer so that the sender could get response messages to confirm actions etc. The program has a class called netctl.cpp and a header netctl.h. When i tried to declare the mutex that i was going to use for the buffer in the header i got a ton of errors. So instead i tried to pass a mutex pointer to the constructor of netctl and that worked.
Is this approach safe/good practice? Otherwise, how would i set it up for this scenario to work?
This works
// launch.cpp
int main(){
std::mutex mtex;
Netctl network_control(&mtex);
std::thread thread_listener(&Netctl::network_listener, network_control);
thread_listener.join();
}
// netctl.cpp
#include "netctl.h"
Netctl::Netctl(std::mutex* m){
mutex = m;
}
Netctl::~Netctl(){}
// netctl.h
#ifndef NETCTL_H
#define NETCTL_H
class Netctl{
public:
Netctl(std::mutex* m);
~Netctl();
private:
std::mutex* mutex;
};
#endif
I expected the example below to work. why does this not work? I understand that mutexes cannot be copied. But why can't i create the mutex in the constructor or in the header?
This does not work
// launch.cpp
int main(){
Netctl network_control();
std::thread thread_listener(&Netctl::network_listener, network_control);
thread_listener.join();
}
// netctl.cpp
#include "netctl.h"
Netctl::Netctl(){
std::mutex mtex; // tried declaring mutex here
}
Netctl::~Netctl(){}
// netctl.h
#ifndef NETCTL_H
#define NETCTL_H
class Netctl{
public:
Netctl();
~Netctl();
private:
std::mutex* mutex; // also tried it here
};
#endif
I'm not very experienced with c++ so i apologize if my question is confusing.