【线程】线程的封装

C++提供有线程库,他的底层其实也是用原生线程库封装的

下面直接看看C++提供的线程库的基本使用

#include <iostream>
#include <thread>
#include <unistd.h>

using namespace std;

void handler()
{
    while (1)
    {
        cout << "main create a thread" << endl;
        sleep(1);
    }
}

int main()
{
    thread t(handler);
    t.join();

    return 0;
}

下面直接进行封装,看看是怎么封装的

main.cc

#include <iostream>
#include <thread>
#include <unistd.h>
#include"thread.hpp"

using namespace std;

void Print()
{
    while(true)
    {
        printf("haha, 我是一个封装的线程...\n");
        sleep(1);
    }
}

int main()
{
    Thread t(Print);
    t.Run();

    cout << "是否启动成功: " << t.IsRunning() << endl;
    cout << "启动成功时间戳: " << t.StartTimestamp() << endl;
    cout << "线程的名字: " << t.Name() << endl;

    t.Join();
    return 0;
}

thread.hpp

#pragma once
#include<iostream>
#include<pthread.h>
#include<string>

using namespace std;

typedef void(*callback_t)();
static int num = 1;


class Thread
{
public:
    Thread(callback_t cb):cb_(cb),isrunning_(false)
    {}

    static void* Routine(void* args)
    {
        Thread* td=static_cast<Thread*>(args);
        td->Enter();
        return nullptr;
    }
    void Run()
    {
        name_="thread-"+to_string(num++);
        start_timestamp_=time(nullptr);
        isrunning_=true;
        pthread_create(&tid_,nullptr,Routine,this);
    }
    void Join()
    {
        pthread_join(tid_,nullptr);
        isrunning_=false;
    }
    string Name()
    {
        return name_;
    }
    uint64_t StartTimestamp()
    {
        return start_timestamp_;
    }
    bool IsRunning()
    {
        return isrunning_;
    }
    void Enter()
    {
        cb_();
    }
    ~Thread()
    {}
private:
    pthread_t tid_;
    string name_;
    uint64_t start_timestamp_;
    bool isrunning_;

    callback_t cb_;//传入的无参无返回值的函数
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲代码的奇点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值