线程基础实践

文章目录

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;
}
相关推荐
霖003 分钟前
ZYNQ——ultra scale+ IP 核详解与配置
服务器·开发语言·网络·笔记·网络协议·tcp/ip
flypwn13 分钟前
justCTF 2025JSpositive_player知识
开发语言·javascript·原型模式
oliveira-time17 分钟前
原型模式中的深浅拷贝
java·开发语言·原型模式
余俊晖21 分钟前
英伟达开源多模态视觉语言模型-Nemotron Nano V2 VL模型架构、训练方法、训练数据
人工智能·算法·语言模型·自然语言处理·多模态
2501_9411114621 分钟前
C++中的原型模式
开发语言·c++·算法
高洁0122 分钟前
国内外具身智能VLA模型深度解析(2)国外典型具身智能VLA架构
深度学习·算法·aigc·transformer·知识图谱
一只会写代码的猫29 分钟前
C# 性能优化:从垃圾回收到多线程并发
jvm·算法
亿坊电商1 小时前
PHP框架的资源管理机制如何优雅适配后台任务?
开发语言·php
VBA63371 小时前
YZ系列工具之YZ09: VBA_Excel之读心术
开发语言
慢慢向上的蜗牛1 小时前
微软vcpkg包管理工具如何使用?
c++·microsoft·vcpkg·跨平台编译