Reputation: 355
I have a program which I am attempting to run a process in a separate thread. Normally I would use Qt for this, but in this particular instance I can't (due to it going on to an embedded device). My concern is whether or not my current implementation will run the thread correctly, or if it will destroy the thread before processing. Below is my code:
int main(){
//code
Processor *x = new Processor;
//other code
x->startThread(s);
//more code which needs to be running seperately
}
Class Processor {
public:
Processor();
void startThread(std::string s);
void myCode(std::string s);
//more stuff
}
void Processor::startThread(std::string s){
std::thread(&Processor::startRecording, s).detach();
}
void Processor::myCode(std::string s){
//lots of code
}
Alternatively, if there is an easier way to start myCode
from the main
function rather than needing to have the class startThread
, please let me know.
Upvotes: 1
Views: 83
Reputation: 3832
I suggest that you make the thread as a Processor
attribute.
#include <iostream>
#include <memory>
#include <string>
#include <thread>
//Processor.h
class Processor {
private:
std::shared_ptr<std::thread> _th;
public:
Processor();
void startThread(std::string s);
void joinThread();
void myCode(std::string s);
void startRecording(std::string s);
//more stuff
};
//Processor.cpp
Processor::Processor() {
}
void Processor::startThread(std::string s) {
_th = std::make_shared<std::thread>(&Processor::startRecording, this, s); // "this" is the first argument ;)
}
void Processor::joinThread() {
_th->join();
}
void Processor::myCode(std::string s) {
//lots of code
}
void Processor::startRecording(std::string s) {
std::cout << "msg: " << s << std::endl;
}
// main.cpp
int main(){
//code
auto x = std::make_unique<Processor>();
//other code
x->startThread("hello");
//more code which needs to be running seperately
x->joinThread();
}
Upvotes: 2