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();
// }
相关推荐
意如流水任东西1 分钟前
Linux开发工具(apt,vim,gcc)
linux·服务器
XMAIPC_Robot3 分钟前
基于RK3568的多网多串电力能源1U机箱解决方案,支持B码,4G等
linux·fpga开发·能源·边缘计算
程序猿小D5 分钟前
第14节 Node.js 全局对象
linux·前端·npm·node.js·编辑器·vim
byte轻骑兵10 分钟前
【C++高级主题】命令空间(五):类、命名空间和作用域
开发语言·c++
忘梓.1 小时前
从二叉树到 STL:揭开 set 容器的本质与用法
开发语言·c++
Antonio9151 小时前
【Linux】 Linux 进程控制
linux·运维·服务器
Alan3161 小时前
qt network 整体框架
c++
thinkMoreAndDoMore2 小时前
linux驱动开发(1)-内核模块
linux·运维·驱动开发
darin_ฅ( ̳• ◡ • ̳)ฅ12 小时前
Linux环境-通过命令查看zookeeper注册的服务
linux·zookeeper
Chuncheng's blog2 小时前
CentOS 7 如何pip3安装pyaudio?
linux·运维·python·centos