1. 需要包含线程头文件:
#include <thread>
2. 定义函数
3. 线程启动函数:
thread t(function, args)
如果函数参数是引用,则需要用std::ref(args)
4. 等待线程结束:
if(t.joinable()) {t.join()};
需要注意的是:如果线程调用函数是成员函数,则需要将函数地址和this加入参数,若外部调用成员函数,则需要将this改称具体对象。
/*
多线程推理设计思路
建议先阅读代码,若有疑问,可点击抖音短视频进行辅助讲解(建议1.5倍速观看)
https://v.douyin.com/NfJ9kYy/
*/
//1. thread
#include<thread>
#include<stdio.h>
#include<iostream>
#include<chrono>
#include<string>
using namespace std;
void worker(int a,string& str){
printf("hello thread\n");
printf("%d\n",a);
// this_thread::sleep_for(chrono::milliseconds(1000));
str = "abc";
}
//类成员函数启用线程
class Infer{
public:
Infer(){
worker_thread_ = thread(&Infer::infer_worker,this);
}
private:
void infer_worker(){
}
private:
thread worker_thread_;
};
int main(){
//利用线程调用函数thread t(function,args...)
//若果是引用,需要用std::ref
string param;
thread t(worker,20,std::ref(param));
//分离线程,取消管理权,将线程交给系统管理,不需要join,程序推出后线程退出,一般不使用,但有时候不得不用
// t.detach();
//等待线程结束
if(t.joinable()){
t.join();
}
cout << param << endl;
return 0;
}
本文详细介绍了C++中如何创建线程、使用线程头文件、调用函数、成员函数线程化,并展示了如何启动、等待线程结束。重点讨论了线程同步与避免数据竞争的问题。附带推荐了相关视频辅助理解。

被折叠的 条评论
为什么被折叠?



