文章目录
封装原生线程
Thread.hpp
#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <ctime>
#include <string>
using namespace std;
typedef void (*callback_t)();
static int num = 1;
class Thread
{
public:
static void *Routine(void *args)
{
Thread *t = static_cast<Thread *>(args);
t->Entery();
return nullptr;
}
public:
Thread(callback_t cb)
: tid_(0), tname_(""), starttime_(0), Isrunning_(false), cb_(cb)
{
}
void Run()
{
tname_ = "thread-" + to_string(num++);
starttime_ = time(nullptr);
Isrunning_ = true;
pthread_create(&tid_, nullptr, Routine, this);
}
void Join()
{
pthread_join(tid_, nullptr);
}
string Name()
{
return tname_;
}
uint64_t StartTime()
{
return starttime_;
}
bool IsRunning()
{
return Isrunning_;
}
void Entery()
{
cb_();
}
~Thread()
{
}
private:
pthread_t tid_;
string tname_;
uint64_t starttime_;
bool Isrunning_;
callback_t cb_;
};
main.cc
#include <iostream>
#include <unistd.h>
#include <vector>
#include "Thread.hpp"
using namespace std;
void print()
{
while (1)
{
cout << "我是一个被封装的线程..." << endl;
sleep(1);
}
}
int main()
{
// 多线程
vector<Thread> threads;
for (int i = 0; i < 5; i++)
{
threads.push_back(Thread(print));
}
for (auto &t : threads)
{
t.Run();
}
for (auto &t : threads)
{
t.Join();
}
// 单线程
// Thread t(print);
// t.Run();
// cout<<"是否启动成功: "<<t.IsRunning()<<endl;
// cout<<"name: "<<t.Name()<<endl;
// cout<<"starttime: "<<t.StartTime()<<endl;
// t.Join();
return 0;
}