运行一个线程

时间:2015-12-09 20:04:38

标签: c++ c++11

我有一个程序,我试图在一个单独的线程中运行一个进程。通常我会使用Qt,但在这个特殊情况下我不能(因为它进入嵌入式设备)。我担心的是我的当前实现是否会正确运行线程,或者它是否会在处理之前销毁线程。以下是我的代码:

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
}

或者,如果有一种更简单的方式从myCode功能启动main而不需要拥有课程startThread,请告知我们。

1 个答案:

答案 0 :(得分:2)

我建议您将该主题设为Processor属性。

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();
}
相关问题