gpt4 book ai didi

c++ - 运行线程

转载 作者:行者123 更新时间:2023-11-30 03:46:14 25 4
gpt4 key购买 nike

我有一个程序,我试图在一个单独的线程中运行一个进程。通常我会为此使用 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 属性。

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

关于c++ - 运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34187984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com