线程基础实践

文章目录

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;
}
相关推荐
1570925113423 分钟前
【无标题】
开发语言·python·算法
稚南城才子,乌衣巷风流29 分钟前
换根法(Rerooting)算法详解
算法
xieliyu.31 分钟前
MySQL 存储过程详解:概念、创建与删除全教程
开发语言·数据库·mysql
晓子文集34 分钟前
Tushare接口文档:期货交易日历(fut_trade_cal)
大数据·算法
2zcode1 小时前
项目文档:基于MATLAB最小二乘支持向量机的睡眠分期智能监测系统设计与实现
开发语言·支持向量机·matlab
王维同学1 小时前
Credential Provider、Filter 与 PLAP 的 CLSID 枚举
c++·windows·安全·注册表
twcc_come1 小时前
安全策略配置实验报告
开发语言·php
2601_963870221 小时前
基于Python的晋江文学城热门作品数据分析与可视化
开发语言·python·数据分析
Carlgood-Minecraft2 小时前
随机分位系统破解版 (BPS)Version-B4.2
c++
^yi2 小时前
【Linux系统编程】进程状态的理解
算法·僵尸进程·孤儿进程·进程状态·挂起状态·阻塞状态