Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 运行线程_C++_C++11 - Fatal编程技术网

C++ 运行线程

C++ 运行线程,c++,c++11,C++,C++11,我有一个程序,我正试图在一个单独的线程中运行一个进程。通常情况下,我会使用Qt来实现这一点,但在这个特殊的例子中,我不能(因为它是在嵌入式设备上实现的)。我关心的是我当前的实现是否会正确运行线程,或者它是否会在处理之前销毁线程。下面是我的代码: int main(){ //code Processor *x = new Processor; //other code x->startThread(s); //more code which needs to be run

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

int main(){
  //code
  Processor *x = new Processor;
  //other code
  x->startThread(s);
  //more code which needs to be running seperately
}
处理器.h 处理器.cpp
或者,如果有更简单的方法从
main
函数启动
myCode
,而不需要类
startThread
,请告诉我。

我建议您将线程设置为
处理器
属性

#包括
#包括
#包括
#包括
//处理器.h
类处理器{
私人:
std::共享的ptr;
公众:
处理器();
void startThread(std::string s);
void joinThread();
void myCode(std::string s);
无效开始记录(标准::字符串s);
//更多的东西
};
//处理器.cpp
处理器::处理器(){
}
空处理器::startThread(std::字符串s){
_th=std::make_shared(&Processor::startRecording,this,s);/“this”是第一个参数;)
}
void处理器::joinThread(){
_th->join();
}
无效处理器::myCode(标准::字符串s){
//很多代码
}
无效处理器::开始记录(标准::字符串s){

std::cout目标设备上运行的是什么操作系统?请阅读一些书籍(c++线程,通常使用“新”)@DieterLück不必太刻薄。为什么不干脆
std::thread thread(&myCode,s);
?可能有一个很好的理由说明你不能这样做,但如果是这样的话,你的问题没有说明任何问题。startRecording()静态成员函数?您可能只希望将
this
作为第一个参数或
std::ref(*this)
。是的。谢谢,它现在已修复。
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
}
#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();
}