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_;//传入的无参无返回值的函数
};