Linux线程库封装

一 MyThread.hpp

#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_;


};

二 测试

#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 线笔记

    2024-02-06 23:02:01       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-06 23:02:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-06 23:02:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-06 23:02:01       82 阅读
  4. Python语言-面向对象

    2024-02-06 23:02:01       91 阅读

热门阅读

  1. C++泛型编程:模板偏特化

    2024-02-06 23:02:01       50 阅读
  2. go语言进阶篇——接口

    2024-02-06 23:02:01       55 阅读
  3. React Emotion 如何优雅的使用样式(一)

    2024-02-06 23:02:01       48 阅读
  4. npm命令

    2024-02-06 23:02:01       49 阅读
  5. Qt应用软件【协议篇】UDP示例

    2024-02-06 23:02:01       47 阅读
  6. elementui上传文件不允许重名

    2024-02-06 23:02:01       49 阅读