正在运行线程
Running a thread
我有一个程序,我正试图在一个单独的线程中运行一个进程。通常情况下,我会使用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();
}
相关文章:
- 为什么std::async使用同一个线程运行函数
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何使线程运行现有类的函数?C++
- 使用 4 个和 8 个线程运行时执行的时间相等
- 在我调用join()之前,std ::线程运行
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- 线程连接在另一个线程运行时会导致分段错误
- 动态提升线程运行存储在具有共享指针的向量中的对象的方法
- 如何启动一个 boost::线程运行一个成员函数
- 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行
- 线程运行时间最少
- 计算线程运行的次数
- MySQL C API:从不同线程运行查询时出现分段错误
- 使用两个线程运行和中断一个无限循环
- 与icc 14一起使用多线程运行时库时的错误
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 发布配置上的Visual Studio c++多线程运行时问题
- 使用逻辑线程运行程序
- 为什么设置 CPU 关联会使线程运行速度变慢