1 Star 1 Fork 0

dinghai/lpzmuduo

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Thread.cc 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
dinghai 提交于 2026-04-28 22:02 +08:00 . add lpzmuduo
#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();
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lpzdinghai/lpzmuduo.git
git@gitee.com:lpzdinghai/lpzmuduo.git
lpzdinghai
lpzmuduo
lpzmuduo
master

搜索帮助