线程基础实践

文章目录

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;
}
相关推荐
码叔义11 分钟前
Jsonpath 使用说明
android·开发语言·javascript
行十万里人生24 分钟前
Qt 对象树详解:从原理到运用
开发语言·数据库·qt·华为od·华为·华为云·harmonyos
原来是猿30 分钟前
蓝桥备赛(四)- 数组(下)
开发语言·数据结构·c++·算法
zjkzjk771132 分钟前
reallocate() 和 allocate() 的区别
c++
心流时间33 分钟前
[Java基础] JVM常量池介绍(BeanUtils.copyProperties(source, target)中的属性值引用的是同一个对象吗)
java·开发语言·jvm
网络安全Ash36 分钟前
Python网络安全脚本
开发语言·python·web安全
ephemerals__41 分钟前
【数据结构进阶】哈希表
数据结构·算法·散列表
.猫的树1 小时前
Java集合List快速实现重复判断的10种方法深度解析
java·开发语言·list·集合
星霜旅人1 小时前
【C++】深入理解List:双向链表的应用
c++
刀客1231 小时前
C++ STL(三)list
开发语言·c++