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();
// }
相关推荐
IT猿手41 分钟前
2025最新群智能优化算法:海市蜃楼搜索优化(Mirage Search Optimization, MSO)算法求解23个经典函数测试集,MATLAB
开发语言·人工智能·算法·机器学习·matlab·机器人
纷飞梦雪2 小时前
使用chroot预安装软件到ubuntu22中
linux·运维·ubuntu
IT猿手3 小时前
2025最新群智能优化算法:山羊优化算法(Goat Optimization Algorithm, GOA)求解23个经典函数测试集,MATLAB
人工智能·python·算法·数学建模·matlab·智能优化算法
小羊在奋斗5 小时前
【Linux网络】NAT技术、DNS系统、五种IO模型
linux·网络·智能路由器
Dream it possible!6 小时前
LeetCode 热题 100_字符串解码(71_394_中等_C++)(栈)
c++·算法·leetcode
jiarg6 小时前
linux 内网下载 yum 依赖问题
linux·运维·服务器
yi个名字7 小时前
Linux第一课
linux·运维·服务器
Kurbaneli7 小时前
深入理解 C 语言函数的定义
linux·c语言·ubuntu
My Li.7 小时前
c++的介绍
开发语言·c++