手写std::thread

背景:

        最近看了罗能大佬的关于可变参数模版的教程,下边是教程中对应thread源码,在它的基础上完善了一些功能

代码

#include <iostream>
#include <memory>
#include <tuple>
#include <pthread.h>
struct thread{
	template<typename F, typename ...Args>
	thread(F f, Args ...args)
	{
		using FnArgs = std::tuple<F, std::tuple<Args...>>;
		std::unique_ptr<FnArgs> uniFnArgs {new FnArgs(f, {args...})};
		int res = pthread_create(&_thread, nullptr, [](void *pUserData)->void *{
				std::unique_ptr<FnArgs> uniFnArgs{static_cast<FnArgs*>(pUserData)};
				auto &[f, args] = *uniFnArgs;
				std::apply(f, args);
				return nullptr;
			}, uniFnArgs.get());
		if (res == 0)
		{
			uniFnArgs.release();
		}
	}
	void join()
	{
		pthread_join(_thread, nullptr);	
	}
private:
	pthread_t _thread;
};
void print(int a, double b, char c)
{
	std::cout<<a<<b<<c<<std::endl;
}
int main()
{
	 thread th(print, 1, 2.0, 'A');
	 th.join();	
	return 0;
}

        上边代码逻辑还是比较清晰的,thread 构造方法,一个函数,其他可变参数,然后把这参数打包成tuple,在和函数一起打包成tuple,pthread创建线程后把,把创建的unique_ptr,里边的指针传递给线程里边,线程里边在做解包操作,最终用apply进行调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值