线程基础实践

文章目录

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;
}
相关推荐
卡戎-caryon6 分钟前
【C++】15.并发支持库
java·linux·开发语言·c++·多线程
90后小陈老师12 分钟前
WebXR教学 09 项目7 使用python从0搭建一个简易个人博客
开发语言·python·web
tyatyatya16 分钟前
MATLAB 神经网络的系统案例介绍
开发语言·神经网络·matlab
hweiyu0027 分钟前
C#学习教程(附电子书资料)
开发语言·学习·c#
q5673152328 分钟前
图片爬虫通过模板及使用说明
开发语言·爬虫·tcp/ip·golang
superior tigre33 分钟前
C++学习:六个月从基础到就业——C++11/14:列表初始化
c++·学习
2301_7944615737 分钟前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠38 分钟前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
正在走向自律40 分钟前
Conda 完全指南:从环境管理到工具集成
开发语言·python·conda·numpy·fastapi·pip·开发工具
啊吧怪不啊吧1 小时前
C/C++之内存管理
开发语言·汇编·c++