Linux线程库封装

一 MyThread.hpp

cpp 复制代码
#pragma once
#include<pthread.h>
#include<iostream>
#include<unistd.h>
#include<string>
#include<ctime>

typedef void (*callback_t)();
static int num = 1;
//任务和线程绑定
class Thread
{
    static void* Routine(void *args)
    {
        Thread* ptr = static_cast<Thread*>(args);
        ptr->Entry();
        return nullptr;
    }
public:
    Thread(callback_t cb)
    :cb_(cb),tname_(""),start_time_stamp_(0),isrunning_(false)
    {}
    ~Thread()
    {}
    void Run()
    {
        tname_ = "thread-" + std::to_string(num);
        start_time_stamp_ = time(nullptr);
        isrunning_ = true;
        pthread_create(&tid_,nullptr,Routine,this);
    }
    void Join()
    {
        pthread_join(tid_,nullptr);
        isrunning_ = false;
    }
    void Entry()
    {
        cb_();
    }
    bool Isrunning()
    {
        return isrunning_;
    }
    std::string Name()
    {
        return tname_;
    }
    uint64_t StartTimeStamp()
    {
        return start_time_stamp_;
    }
private:
    pthread_t tid_;
    std::string tname_;
    callback_t cb_;//回调函数
    uint64_t start_time_stamp_;
    bool isrunning_;


};

二 测试

cpp 复制代码
#include "MyThread.hpp"
#include <vector>
void task()
{
    while (1)
    {
        std::cout << "I am a task" << std::endl;
        sleep(1);
    }
}

int main()
{
    std::vector<Thread> threads;
    for (int i = 0; i < 10; ++i)
    {
        threads.push_back(Thread(task));
    }
    for (auto &t : threads)
    {
        t.Run();
    }
    for (auto &t : threads)
    {
        t.Join();
    }
}
// int main()
// {
//     Thread t1(task);
//     std::cout << "name:" << t1.Name() << " time:" << t1.StartTimeStamp()
//               << " isrun??  " << t1.Isrunning() << std::endl;
//     t1.Run();
//     std::cout << "name:" << t1.Name() << " time:" << t1.StartTimeStamp()
//               << " isrun??  " << t1.Isrunning() << std::endl;
//     t1.Join();
// }
相关推荐
涛ing16 分钟前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
__雨夜星辰__17 分钟前
Linux 学习笔记__Day2
linux·服务器·笔记·学习·centos 7
大耳朵土土垚18 分钟前
【Linux】日志设计模式与实现
linux·运维·设计模式
独正己身1 小时前
代码随想录day4
数据结构·c++·算法
我不是代码教父3 小时前
[原创](Modern C++)现代C++的关键性概念: 流格式化
c++·字符串格式化·流格式化·cout格式化
利刃大大4 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
子燕若水4 小时前
mac 手工安装OpenSSL 3.4.0
c++
*TQK*4 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
Rachela_z4 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@5 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法