部署中的线程

本文详细介绍了C++中如何创建线程、使用线程头文件、调用函数、成员函数线程化,并展示了如何启动、等待线程结束。重点讨论了线程同步与避免数据竞争的问题。附带推荐了相关视频辅助理解。

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值