线程基础实践

文章目录

1.创建线程和join

2.detach分离线程

3.线程传递参数

4.获取线程id

5.线程休眠

6.结束线程

cpp 复制代码
#include <iostream>
#include <thread>
#include <string>
#include <functional>
#include <unistd.h>

using namespace std;

/*
 * 1.创建线程和join
 * 2.detach分离线程
 * 3.线程传递参数
 * 4.获取线程id
 * 5.线程休眠
 * 6.结束线程
 * */

void show(){
    for (int i = 0; i < 3; ++i) {
        cout << __func__ << "=" << i << endl;
        this_thread::sleep_for(chrono::seconds(1));
    }
}

class stu{
public:
    string name;
    int age;

    stu(const string &name,int age):name(name),age(age){
        cout << "构造函数"<< name << age << endl;
    }

    void work(string name,int age){
        cout << "执行学生工作"<< endl;
        stu s(name,age);
    }
};

void print(){
    cout << "meet to---"<< endl;
}

void call(){
    for (int i = 0; i < 3; ++i) {
        cout << "呼叫"<<i << endl;
        usleep(1000*1000);
    }
}

void sendMsg(){
    for (int i = 0; i < 5; ++i) {
        if(i==3){
            cout<< "线程终止"<< endl;
            return;
        }
    }
}

int main() {
    thread t(show);
    cout << "执行main"<<endl;
    t.join();

    thread t2(show);
    t2.detach();

    stu s("小明",16);
    thread t3(bind(&stu::work,&s,s.name,s.age));
    this_thread::sleep_for(chrono::seconds(5));
    t3.join();

    cout << "主线程id="<<this_thread::get_id << endl;
    thread t4(print);
    t4.get_id();
    t4.join();

    thread t5(call);
    t5.join();

    thread t6(sendMsg);
    t6.join();

    return 0;
}
相关推荐
Wang's Blog7 分钟前
Lua: 核心机制解析之函数的多维魔法与模块化封装艺术
开发语言·lua
虾..28 分钟前
Linux 简单日志程序
linux·运维·算法
小高Baby@30 分钟前
使用Go语言中的Channel实现并发编程
开发语言·后端·golang
Trent198536 分钟前
影楼精修-眼镜祛反光算法详解
图像处理·人工智能·算法·计算机视觉·aigc
蓝色汪洋37 分钟前
经典修路问题
开发语言·c++·算法
csuzhucong1 小时前
122魔方、123魔方
算法
ss2731 小时前
ThreadPoolExecutor:自定义线程池参数
java·开发语言
我有一棵树1 小时前
解决 highlight.js 不支持语言的方法
开发语言·javascript·ecmascript
Salt_07281 小时前
DAY 40 早停策略和模型权重的保存
人工智能·python·算法·机器学习
卜锦元1 小时前
Golang后端性能优化手册(第三章:代码层面性能优化)
开发语言·数据结构·后端·算法·性能优化·golang