代码拉取完成,页面将自动刷新
#include "Thread.h"
#include "CurrentThread.h"
#include <future>
std::atomic_int Thread::numCreated_{0};
Thread::Thread(ThreadFunc func, const std::string& name)
:name_(name)
, tid_(0)
, func_(func)
{
setDefaultName();
}
Thread::~Thread()
{
if(thread_ && thread_->joinable())
{
thread_->detach();
}
}
void Thread::join()
{
if(thread_ && thread_->joinable())
{
thread_->join();
}
}
void Thread::setDefaultName()
{
int num = ++numCreated_;
if(name_.empty())
{
char buf[32] = { 0 };
snprintf(buf, sizeof buf, "Thread%d", num);
name_ = buf;
}
}
// 启动线程,并保证 tid_ 赋值完成才返回
void Thread::start() {
// 1. 创建 promise,用于线程间传递 系统TID
std::promise<pid_t> prom;
// 2. 获取 future,用来等待值的到来
std::future<pid_t> fut = prom.get_future();
// 3. 创建线程,lambda 捕获 this 和 prom
thread_ = std::make_unique<std::thread>([this, &prom]() {
pid_t sys_tid = CurrentThread::tid();
// 把 TID 传给主线程,并唤醒等待的主线程
prom.set_value(sys_tid);
// 执行用户传入的线程业务函数
func_();
});
tid_ = fut.get();
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。