正在运行线程

Running a thread

本文关键字:线程 运行      更新时间:2023-10-16

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

int main(){
  //code
  Processor *x = new Processor;
  //other code
  x->startThread(s);
  //more code which needs to be running seperately
}

处理器.h

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

处理器.cpp

void Processor::startThread(std::string s){
  std::thread(&Processor::startRecording, s).detach();
}
void Processor::myCode(std::string s){
  //lots of code
}

或者,如果有一种更简单的方法可以从main函数启动myCode,而不需要类startThread,请告诉我。

我建议您将线程作为Processor属性。

在线运行

#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();
}