user3830784
user3830784

Reputation: 355

Running a thread

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
}

Processor.h

Class Processor {
public:
  Processor();
  void startThread(std::string s);
  void myCode(std::string s);
  //more stuff
}

Processor.cpp

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

Answers (1)

maddouri
maddouri

Reputation: 3832

I suggest that you make the thread as a Processor attribute.

Run It Online

#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

Related Questions