(46)模板类 promise《T》 的源代码:,对此泛化版本进行了详细的注释:
// _State_manager { _Associated_state<_Ty>* _Assoc_state; bool _Get_only_once ; } ;
// _State_manager<T> 对象,即是其子类 future<T>、share_future<T> 中的对象成员;
// 也是 _Promise<T> 中的数据成员,也是 promise<U>、promise<U&>、promise<void> 中的数据对象成员。
// 区别是:函 async(..) 调用时,爷指针指向孙对象;
// : packaged_task<R(a…)> 对象在 thread 线程中调用时,爷指针指向爹对象;
// : promise<M> 在线程中调用时,爷指针指向爷对象自己,仅存储一个线程安全的线程间共享的数据。
template <class _Ty> // class that defines an asynchronous provider that holds a value
class promise // 类的实例,它定义了一个异步提供程序,该提供程序保存一个值
{
private:
_Promise<_Ty> _MyPromise; // _Promise<_Ty> { _State_manager<_Ty> _State; bool _Future_retrieved; };
public:
/*
template <class>
bool is_reference_v = false; // determine whether type argument is a reference
template <class _Ty>
bool is_reference_v<_Ty&> = true;
template <class _Ty>
bool is_reference_v<_Ty&&> = true;
//--------------------------------------------------------------------
template <class>
bool is_const_v = false; // determine whether type argument is const qualified
template <class _Ty> // 若类型被 const 修饰,则为 true 。但也有编译器规定的例外情形
bool is_const_v<const _Ty> = true; // 函数类型和引用类型就是被 const 修饰,也是 False
//-----------------------------------------------------------------
// only function types and reference types can't be const qualified
template <class _Ty>
bool is_function_v = !is_const_v<const _Ty> && !is_reference_v<_Ty>;
template <class _Ty> // 这就排除了函数类型与引用类型,又非 void ,即为所谓的对象类型
bool is_object_v = is_const_v<const _Ty> && !is_void_v<_Ty>;
template <class _Ty> // 经测试,函数类型与 void 返回 F,其余类型还有引用都返回 T
bool is_destructible_v = __is_destructible(_Ty);
*/
// 此行判断,要求 _Ty 非数组类型,非函数类型,非引用类型,非 void;且可析构
// 这个判断,也是为了区分本模板的特化类型。函数的返回值是引用或 void 时,由本模板的特化版本处理。
static_assert(!is_array_v<_Ty>&& is_object_v<_Ty>&& is_destructible_v<_Ty>,
"T in promise<T> must meet the Cpp17Destructible requirements (N4878 [futures.promise]/1).");
promise() : _MyPromise(new _Associated_state<_Ty>) {} // 默认构造函数
template <class _Alloc> // 指定类对象的分配器的有参构造函数
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<_Ty>(_Al)) {}
promise(const promise&) = delete; // 禁止 copy 构造函数
promise& operator=(const promise&) = delete; // 禁止 copy 赋值运算符函数
promise(promise&& _Other) : _MyPromise(_STD move(_Other._MyPromise)) {} // 移动构造函数
promise& operator=(promise&& _Other) noexcept // 移动赋值运算符函数
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept // 析构函数。本函数的执行,不会导致进程异常退出
{ // 意思是在没有计算出函数返回值前,本 promise 对象被析构了,则在 _Associated_state<_Ty> 中记录异常情况
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) { _MyPromise._Swap(_Other._MyPromise); }
// class _Promise
// { _State_manager<_Ty>& _Get_state_for_future() { _Future_retrieved = true; return _State; } };
future<_Ty> get_future()
{
return future<_Ty>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value(const _Ty& _Val) // copy 的语义
{
_MyPromise._Get_state_for_set()._Set_value(_Val, false);
}
void set_value(_Ty&& _Val) // 移动的语义
{
_MyPromise._Get_state_for_set()._Set_value(_STD forward<_Ty>(_Val), false);
}
void set_value_at_thread_exit(const _Ty& _Val) // copy 的语义
{
_MyPromise._Get_state_for_set()._Set_value(_Val, true);
}
void set_value_at_thread_exit( _Ty&& _Val) // 移动的语义
{
_MyPromise._Get_state_for_set()._Set_value(_STD forward<_Ty>(_Val), true);
}
void set_exception(exception_ptr _Exc) // 填写 _Associated_state<T>._Exception 成员
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
(47) 模板类 promise<T&> 的源代码 :
template <class _Ty> // class that defines an asynchronous provider that holds a reference
class promise<_Ty&> // 类的实例,该实例定义了一个包含引用的异步提供程序
{
private:
_Promise<_Ty*> _MyPromise; // 特化模板类,转换了存储的函数风返回值类型
public:
promise() : _MyPromise(new _Associated_state<_Ty*>) {}
template <class _Alloc>
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<_Ty*>(_Al)) {}
promise(const promise&) = delete;
promise& operator=(const promise&) = delete;
promise(promise&& _Other) noexcept : _MyPromise(_STD move(_Other._MyPromise)) {}
promise& operator=(promise&& _Other) noexcept
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept
{
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) noexcept { _MyPromise._Swap(_Other._MyPromise); }
future<_Ty&> get_future()
{
return future<_Ty&>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value(_Ty& _Val)
{
_MyPromise._Get_state_for_set()._Set_value(_STD addressof(_Val), false);
}
void set_value_at_thread_exit(_Ty& _Val)
{
_MyPromise._Get_state_for_set()._Set_value(_STD addressof(_Val), true);
}
void set_exception(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
(48) 模板类 promise《void》 的源代码 :
template <> // 定义不保存值的异步提供程序
class promise<void> // defines an asynchronous provider that does not hold a value
{
private:
_Promise<int> _MyPromise; // 特化模板类,转换了存储的函数风返回值类型
public:
promise() : _MyPromise(new _Associated_state<int>) {}
template <class _Alloc>
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<int>(_Al)) {}
promise(const promise&) = delete;
promise& operator=(const promise&) = delete;
promise(promise&& _Other) noexcept : _MyPromise(_STD move(_Other._MyPromise)) {}
promise& operator=(promise&& _Other) noexcept
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept
{
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) noexcept { _MyPromise._Swap(_Other._MyPromise); }
future<void> get_future()
{
return future<void>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value()
{
_MyPromise._Get_state_for_set()._Set_value(1, false);
}
void set_value_at_thread_exit()
{
_MyPromise._Get_state_for_set()._Set_value(1, true);
}
void set_exception(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
(49) 整个源文件的源代码,共 2000 行,带完整的注释,更详细的注释见第一篇文(有 6000 行):
#pragma once
#ifndef _FUTURE_
#define _FUTURE_
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR
#ifdef _M_CEE
#error <future> is not supported when compiling with /clr or /clr:pure.
#endif // _M_CEE
#include <__msvc_chrono.hpp>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <ppltasks.h>
#include <system_error>
#include <thread>
#include <utility>
#pragma pack(push, _CRT_PACKING)
// 以下的结构体以及 union 将采用 8 字节对齐。入栈原来的对齐方式 _CRT_PACKING = 8
#pragma warning(push, _STL_WARNING_LEVEL)
// 调整本源文件编译时候的警告级别,是较减少了警告。 _STL_WARNING_LEVEL = 3
// 0 不警告,4 全警告。并把原来的警告级别入栈
#pragma warning(disable : _STL_DISABLED_WARNINGS)
// #define _STL_DISABLED_WARNINGS 4180 4412 4455 4494 4514 4574 ......
// 表示禁用这些警告,忽略这些警告 <yvals_core.h>
_STL_DISABLE_CLANG_WARNINGS
// 按字面意思,禁止 clang 警告,最后还有对应的 宏定义,_STL_RESTORE_CLANG_WARNINGS
#pragma push_macro("new")
#undef new
// 入栈系统之前的 new 的宏定义,并取消此宏定义。可能要自己定义内存管理方式
_STD_BEGIN
// #define _STD_BEGIN namespace std { 表示以下内容全部定义于 std 命名空间
//*******************************以下是一些辅助分析的类****************************************************
// names for timed wait function returns // 定义了一个枚举类
enum class future_status { ready, timeout, deferred } ;
// 函数返回值已准备好,函数正在执行中,函数被延期执行(还未启动)
[[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Throw_future_error(const error_code& _Code);
[[noreturn]] _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Rethrow_future_exception(exception_ptr _Ptr);
// names for launch options passed to async 传递给异步的启动选项的名称
// async 表在调用 async 函数时就创建并执行线程(强制异步任务在新线程中执行)
// deferred 表线程入口函数的执行被延迟到 future 对象的 wait 或 get 执行时,可能不创建新线程
// async | deferred 表两种执行方式都可以,系统自己决定
enum class launch { async = 0x1, deferred = 0x2 } ;
/*
// 确定 _Ty 是否为枚举类型 determine whether _Ty is an enumerated type
template <class _Ty>
struct is_enum : bool_constant< __is_enum(_Ty) > {};
template <class _Ty>
constexpr bool is_enum_v = __is_enum(_Ty);
//---------------------------------------
template <class _Ty, bool = is_enum_v<_Ty>>
struct _Underlying_type { using type = __underlying_type(_Ty) ; };
template <class _Ty>
struct _Underlying_type<_Ty, false> {};
template <class _Ty> // 确定枚举的基础类型 determine underlying根本的 type for enum
struct underlying_type : _Underlying_type<_Ty> {};
template <class _Ty>
using underlying_type_t = typename _Underlying_type<_Ty>::type;
*/
// _BITMASK_OPS(launch) 这是原有的宏函数定义,展开如下,定义了支持枚举类 launch 成员运算的函数。
// 该宏函数定义来源于 <type_traits>
constexpr launch operator & (launch _Left, launch _Right) noexcept // return _Left & _Right
{ using _IntTy = _STD underlying_type_t<launch>; // 经测试 _IntTy 就是 int 类型,推导见上面的注释
return static_cast<launch>(static_cast<int>(_Left) & static_cast<int>(_Right));
} // 以下函数采用简化类型,突出重点。枚举类型只支持与运算,或运算,异或运算,取反运算
launch operator | (launch _Left, launch _Right) noexcept // return _Left | _Right
{ return static_cast<launch>(static_cast<int>(_Left) | static_cast<int>(_Right)); }
launch operator^(launch _Left, launch _Right) noexcept // return _Left ^ _Right
{ return static_cast<launch>(static_cast<int>(_Left) ^ static_cast<int>(_Right)); }
// return _Left &= _Right 注意:这仨复合运算符函数的形参 1 是左值引用,返回值也是左值引用
launch& operator &= (launch& _Left, launch _Right) { return _Left = _Left & _Right; }
// return _Left |= _Right 调用举例:需使用显式的复合运算符调用, A e &= A a;会报错(与 & 混淆了)
launch& operator |= (launch& _Left, launch _Right) { return _Left = _Left | _Right; }
// return _Left ^= _Right 调用举例:A f = operator^=(A::c, A::a);
launch& operator ^= (launch& _Left, launch _Right) { return _Left = _Left ^ _Right; }
// return ~_Left _BITMASK_OPS(launch)的展开结果
launch operator ~ (launch _Left) { return static_cast<launch>(~static_cast<int>(_Left)); }
// return (_Left & _Elements) != launch{} 按位与,测试形参 1 与 2 之间是否有数值重叠,即为包含
bool _Bitmask_includes(launch _Left, launch _Elements) { return (_Left & _Elements) != launch{}; }
// 注意:这俩函数的函数名是固定的,使用了小写字母,与宏函数的形参无关
// return (_Left & _Elements) == _Elements 按位与,测试形参1 是否全部包含了形参 2 的每一位
bool _Bitmask_includes_all(launch _Left, launch _Elements) { return (_Left & _Elements) == _Elements; }
//************************************************************************************************
template <class _Ty> // abstract base class for managing deletion of state objects
struct __declspec(novtable) _Deleter_base
{
virtual void _Delete(_Associated_state<_Ty>*) = 0; // 纯虚函数,形参是父类指针指向子类对象
virtual ~_Deleter_base() noexcept {} // 虚析构函数
};
template <class _Ty, class _Derived, class _Alloc> // manage allocator and deletion state objects
struct _State_deleter : _Deleter_base<_Ty> // 仅当为 _Associated_state<T> 中的 T指定分配器与删除器时才有用
{
_Alloc _My_alloc;
_State_deleter(const _Alloc& _Al) : _My_alloc(_Al) {} // 构造函数
_State_deleter(const _State_deleter&) = delete; // 禁止 copy 构造函数
_State_deleter& operator=(const _State_deleter&) = delete; // 禁止 copy 赋值运算符函数
template <class _Ty, class _Derived, class _Alloc> // delete _State and this using stored allocator
void _Delete( _Associated_state<_Ty>* _State) override // 重写父类中的虚函数
{
using _State_allocator = _Rebind_alloc_t<_Alloc, _Derived>;
_State_allocator _St_alloc(_My_alloc);
using _Deleter_allocator = _Rebind_alloc_t<_Alloc, _State_deleter>;
_Deleter_allocator _Del_alloc(_My_alloc);
_Derived* _Ptr = static_cast<_Derived*>(_State);
/*
template <class _Alloc> // deallocate a plain pointer using an allocator 回收内存
void _Deallocate_plain(_Alloc& _Al, typename _Alloc::value_type* const _Ptr) noexcept
{
using _Alloc_traits = allocator_traits<_Alloc>;
if constexpr (is_same_v<_Alloc_ptr_t<_Alloc>, typename _Alloc::value_type*>)
_Alloc_traits::deallocate(_Al, _Ptr, 1);
else
{
using _Ptr_traits = pointer_traits<_Alloc_ptr_t<_Alloc>>;
_Alloc_traits::deallocate(_Al, _Ptr_traits::pointer_to(*_Ptr), 1);
}
}
// destroy *_Ptr in place, then deallocate _Ptr using _Al;
// used for internal container types the user didn't name
// 将 *_Ptr 销毁到位,然后使用 _Al 释放 _Ptr ;用于内部用户未命名的容器类型
template <class _Alloc> // 总之就是先执行 _Ty 类型对象的析构函数,再回收内存。
void _Delete_plain_internal(_Alloc& _Al, typename _Alloc::value_type* const _Ptr) noexcept
{
using _Ty = typename _Alloc::value_type;
_Ptr->~_Ty();
_Deallocate_plain(_Al, _Ptr);
}
*/
_Delete_plain_internal(_St_alloc, _Ptr);
_Delete_plain_internal(_Del_alloc, this);
}
};
//******************************************************************************************************
//-------------------------------------------------------------------------------------------------------------
//--下面这一段是爷类 _Associated_state 与子类 _Packaged_state 与孙类 _Deferred_async_state + _Task_async_state
//-------------------------------------------------------------------------------------------------------------
template <class _Ty> // 模板参数 _Ty 与线程中执行的函数的返回值类型有关。本类的对象建立在堆区。
class _Associated_state // class for managing associated synchronous state 用于管理关联同步状态的类
{
public:
using _State_type = _Ty; // 函数返回值则 _Ty是对象类型; 返回左值引用则 _Ty是地址; 返回 void则 _Ty是 int
using _Mydel = _Deleter_base<_Ty>;
_Ty _Result; // 当执行函数没有返回值, 则 _Ty 是 int , result 取值为 1 ,表函数执行成功。
exception_ptr _Exception;
mutex _Mtx; // 线程获得锁以后才可以读写 _Associated_state 指针指向对象的这些数据成员
condition_variable _Cond; // 用于线程同步
bool _Retrieved; // 表函数返回值是否被读取过
int _Ready; // 表示函数返回值是否已计算好,可以等待读取了, 初始化为 0 = false ,未准备好
bool _Ready_at_thread_exit; // 是否要待线程结束才允许函数返回值被读取,但代码里貌似未使用,可以用 !_Ready 替代
bool _Has_stored_result; // 先后将 _Has_stored_result 与 _Ready 都设置后外界才可以读取函数返回值
bool _Running; // 表计算函数返回值的线程是否已启动执行,初始化为 false
private:
_Atomic_counter_t _Refs; // using _Atomic_counter_t = unsigned long;
// future 的父类 _State_manager 的 copy 构造与赋值运算符函数,就是仅仅将 _Refs 加一。堆区仅有此一份结果。
_Mydel* _Deleter; // 初始化为 nullptr ,表程序员未使用自己编写的 删除器 ,用的系统默认版本。
void _Delete_this() // delete this object 销毁本模板类的对象自身(也存在父类指针指向子类对象)
{
if (_Deleter) _Deleter->_Delete(this);
else delete this;
}
// overridden by _Deferred_async_state 这俩虚函数仅由孙类 _Deferred_async_state 进行了重定义
// 字面意思就是线程中的函数是否被延迟执行了,是则返回 true
virtual bool _Has_deferred_function() const noexcept { return false; }
/*
template <class _Rx> // 用于管理从异步延迟执行的关联同步状态的类, 此类改写了这俩虚函数
class _Deferred_async_state : public _Packaged_state<_Rx()> // 本类是 _Associated_state 的孙子类
{
virtual bool _Has_deferred_function() override { return ! this->_Running; }
virtual void _Run_deferred_function(unique_lock<mutex>& _Lock) override // run the deferred function
{
_Lock.unlock();
_Packaged_state<_Rx()>::_Call_immediate();
_Lock.lock();
}
};
template <class _Ty>
class _Associated_state
{
virtual void _Run_deferred_function(unique_lock<mutex>&) {} // do nothing 由子类重写这个函数
void _Maybe_run_deferred_function(unique_lock<mutex>& _Lock) // 运行一个延迟函数(如果还没有完成)
{
if (!_Running) // run the function
{
_Running = true;
_Run_deferred_function(_Lock);
}
}
};
*/
virtual void _Run_deferred_function(unique_lock<mutex>&) {} // do nothing 由子类重写这个函数
protected:
// set ready status at thread exit 未见到哪里调用了此函数。本函就是给 _Ready 成员赋值了
void _Make_ready_at_thread_exit() { if (_Ready_at_thread_exit) _Ready = true; }
// run a deferred function if not already done // 运行一个延迟函数(如果还没有完成)
void _Maybe_run_deferred_function(unique_lock<mutex>& _Lock)
{ // 对于正在运行的线程中的函数,本函什么也不做
if (!_Running) { _Running = true; _Run_deferred_function(_Lock); }
}
public:
// non-atomic initialization 构造函数。本类默认模板参数 _Ty 是可构造的,对 _Ty 采用默认构造。
_Associated_state(_Mydel* _Dp = nullptr) : _Refs(1), _Exception(), _Retrieved(false), _Ready(false),
_Ready_at_thread_exit(false), _Has_stored_result(false), _Running(false), _Deleter(_Dp) { }
_Associated_state(const _Associated_state&) = delete; // 禁止 copy 构造函数
_Associated_state& operator=(const _Associated_state&) = delete; // 禁止 copy 赋值运算符
virtual ~_Associated_state() noexcept // registered for release at thread exit 析构函数
{ // 本类存储了线程中函数的返回值。若本类析构时函数返回值没 ready,则不再执行条件变量的唤醒操作
if (_Has_stored_result && !_Ready) { _Cond._Unregister(_Mtx); }
}
void _Retain() { _MT_INCR(_Refs); } // increment reference count 原子性的递增对本对象的引用计数
// decrement reference count and destroy when zero 原子性的递减变量的值
void _Release() { if (_MT_DECR(_Refs) == 0) _Delete_this(); }
// 当没有别处继续引用本对象时,销毁、析构本储存函数返回值的堆区对象。
public:
bool _Is_ready() const { return _Ready != 0; } // 也可直接返回 _Ready,进行默认的类型转换
bool _Is_ready_at_thread_exit() const { return _Ready_at_thread_exit; }
bool _Already_has_stored_result() const { return _Has_stored_result; }
bool _Already_retrieved() const { return _Retrieved; }
void _Abandon() // 本函的语义可能是当没计算出函数返回值时,本对象就被析构释放,
{ // 则设置 _Associated_state<T>._Exception 成员,以记录此异常情况。
unique_lock<mutex> _Lock(_Mtx);
// 经测试本函代码的完整执行,仍是正常情况,不会导致进程出错退出。
if (!_Has_stored_result) {
future_error _Fut(make_error_code(future_errc::broken_promise));
_Set_exception_raw(_STD make_exception_ptr(_Fut), &_Lock, false);
}
}
//********以下函数是一组,等待与限时等待********
// 调用本函数的线程会睡眠等待,等待函数返回值的生成。future.wait() 的调用会传递到本函数
virtual void _Wait() // wait for signal 本函会促使函数执行, 以求返回值
{
unique_lock<mutex> _Lock(_Mtx);
_Maybe_run_deferred_function(_Lock); // 执行线程中的函数,以得到返回值
while (!_Ready) _Cond.wait(_Lock); // 循环,直到函数的返回值被准备好
}
struct _Test_ready // wraps _Associated_state 类中类,下面的函数会用到
{
const _Associated_state* _State;
_Test_ready(const _Associated_state* _St) : _State(_St) {} // 有参构造函数
bool operator()() const { return _State->_Ready != 0; } // 已 ready 则返回 true
};
// enum class future_status { ready , timeout , deferred };
template <class _Rep, class _Per> // wait for duration
future_status _Wait_for(const chrono::duration<_Rep, _Per>& _Rel_time)
{
unique_lock<mutex> _Lock(_Mtx);
if (_Has_deferred_function()) return future_status::deferred; // 延时执行的函数
if (_Cond.wait_for(_Lock, _Rel_time, _Test_ready(this)))
return future_status::ready; // 函数已经执行完毕,返回值已经准备好了
return future_status::timeout; // 正在执行的函数,还没有返回值
}
template <class _Clock, class _Dur> // wait until time point
future_status _Wait_until(const chrono::time_point<_Clock, _Dur>& _Abs_time)
{
unique_lock<mutex> _Lock(_Mtx);
if (_Has_deferred_function()) return future_status::deferred;
if ( _Cond.wait_until(_Lock, _Abs_time, _Test_ready(this)) )
return future_status::ready;
return future_status::timeout;
}
//***************************************
// 本函数可以被子类修改,但目前并没有被三个子类修改,所以本代码有效
// 形参表示,本类中的函数返回值,是否只允许被读取一次
virtual _Ty& _Get_value( bool _Get_only_once )
{
unique_lock<mutex> _Lock(_Mtx);
if (_Get_only_once && _Retrieved)
_Throw_future_error(make_error_code(future_errc::future_already_retrieved));
if (_Exception) _Rethrow_future_exception(_Exception);
_Retrieved = true;
_Maybe_run_deferred_function(_Lock); // 可见,本函也会驱使函数的执行,以获取函数返回值
while (!_Ready) _Cond.wait(_Lock); // 直到函数的返回值准备好了,才返回,才会醒来
if (_Exception) _Rethrow_future_exception(_Exception);
return _Result;
}
//******把函数的返回值存入本结构体*********
private:
// notify waiting threads, This is virtual, but never overridden. 此是虚函数,但从没被改写过
virtual void _Do_notify(unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
_Has_stored_result = true; // 此数据成员显示已计算出函数返回值 , 而 _Ready 表示其它线程可以读取此返回值,分的很细。
if (_At_thread_exit) // notify at thread exit 要求在计算函数返回值的线程退出时,才对外显示 ready 可以读取返回值了
_Cond._Register(*_Lock, &_Ready); // 线程退出时还会检查 _Ready 的值,为 true 才进行唤醒操作么??
else // notify immediately
{
_Ready = true; // 反之,则是在函数返回值计算出来后立马填写 _Associated_state 的数据成员 _Ready
_Cond.notify_all();
}
}
public:
// store a (void) result while inside a locked block 对应于函数的返回值是 void 的情形
void _Set_value_raw(unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result) // 形参2 _At_thread_exit 只是为了传递给另一成函 _Do_notify(...)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_value_raw(const _Ty& _Val, unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Result = _Val; // 函数的返回值的 copy 赋值运算符函数
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_value_raw(_Ty&& _Val, unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Result = _STD forward<_Ty>(_Val); // 函数的返回值的 移动 赋值运算符函数
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_value(const _Ty& _Val, bool _At_thread_exit) // copy 得到的函数返回值
{
unique_lock<mutex> _Lock(_Mtx);
_Set_value_raw(_Val, &_Lock, _At_thread_exit);
}
void _Set_value( _Ty&& _Val , bool _At_thread_exit) // 移动 得到的函数返回值
{
unique_lock<mutex> _Lock(_Mtx);
_Set_value_raw(_STD forward<_Ty>(_Val), &_Lock, _At_thread_exit);
}
void _Set_value(bool _At_thread_exit) // store a (void) result
{
unique_lock<mutex> _Lock(_Mtx); // 函数的返回值是 void
_Set_value_raw(&_Lock, _At_thread_exit);
}
//******以下貌似是处理异常情况,用的不多*******
// store a result while inside a locked block
void _Set_exception_raw(exception_ptr _Exc, unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Exception = _Exc; // 给本类的 _Exception 成员赋值,而不是给 _Result 成员赋值
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_exception(exception_ptr _Exc, bool _At_thread_exit) // store a result
{
unique_lock<mutex> _Lock(_Mtx);
_Set_exception_raw(_Exc, &_Lock, _At_thread_exit);
}
};
//*********************************************************************************************************
// 模板参数的类型为线程中函数的类型 Ret(_ArgTypes...)、Ret&(_ArgTypes...)、void(_ArgTypes...)
template <class> // 这应该是泛型类的泛型版本,若不需要实例化,可以只声明,不定义
class _Packaged_state; // 本父类系列模板没有修改爷爷类中的虚函数
template <class _Ret, class... _ArgTypes> // 本类是 _Associated_state<_Ret> 的子类
class _Packaged_state<_Ret(_ArgTypes...)> : public _Associated_state<_Ret>
{
private: // function 对象,包裹可调用对象
function<_Ret(_ArgTypes...)> _Fn; // 传递来的 _Fake_no_copy_callable_adapter 是可调用对象
public:
using _Mybase = _Associated_state<_Ret>; // 父类
using _Mydel = typename _Mybase::_Mydel;
template <class _Fty2>
_Packaged_state(const _Fty2& _Fnarg) : _Fn(_Fnarg) {} // 有参构造函数
template <class _Fty2> // 采用的是这个万能引用的版本, 有参构造函数
_Packaged_state(_Fty2&& _Fnarg) : _Fn(_STD forward<_Fty2>(_Fnarg)) {}
const function<_Ret(_ArgTypes...)>& _Get_fn() { return _Fn; } // 返回左值引用
// 每种类型的函数(返回值的类型不同), 都有延迟执行和立即执行的两种情况
void _Call_deferred(_ArgTypes... _Args) // set deferred call
{
_TRY_BEGIN // call function object and catch exceptions
this->_Set_value(_Fn(_STD forward<_ArgTypes>(_Args)...), true);
_CATCH_ALL // function object threw exception; record result
this->_Set_exception(_STD current_exception(), true);
_CATCH_END
}
// 父类的各个版本的成函 _Set_value(...) 的最后一个参数都是 bool _At_thread_exit
void _Call_immediate(_ArgTypes... _Args) // call function object
{
_TRY_BEGIN //= try {
this->_Set_value(_Fn(_STD forward<_ArgTypes>(_Args)...), false);
_CATCH_ALL //= } catch (...) { // 这是可变参数包类型
this->_Set_exception(_STD current_exception(), false);
_CATCH_END
} // 本函中,把线程里的函数执行了
};
// 本类是 _Associated_state<_Ret*> 的子类 ,注意定义的时候对函数的返回值类型做了转换为指针
template <class _Ret, class... _ArgTypes>
class _Packaged_state<_Ret& (_ArgTypes...)> : public _Associated_state<_Ret*>
{
private:
function<_Ret& (_ArgTypes...)> _Fn;
public:
using _Mybase = _Associated_state<_Ret*>;
using _Mydel = typename _Mybase::_Mydel;
template <class _Fty2> // 有参构造函数
_Packaged_state(const _Fty2& _Fnarg) : _Fn(_Fnarg) {}
template <class _Fty2> // 有参构造函数
_Packaged_state(_Fty2&& _Fnarg) : _Fn(_STD forward<_Fty2>(_Fnarg)) {}
const function<_Ret& (_ArgTypes...)>& _Get_fn() { return _Fn; }
void _Call_deferred(_ArgTypes... _Args) // set deferred call
{
_TRY_BEGIN // 对函数的返回值取地址
this->_Set_value(_STD addressof(_Fn(_STD forward<_ArgTypes>(_Args)...)), true);
_CATCH_ALL
this->_Set_exception(_STD current_exception(), true);
_CATCH_END
}
void _Call_immediate(_ArgTypes... _Args) // call function object
{
_TRY_BEGIN // 父类中的 void _Set_value ( bool _At_thread_exit )
this->_Set_value(_STD addressof(_Fn(_STD forward<_ArgTypes>(_Args)...)), false);
_CATCH_ALL
this->_Set_exception(_STD current_exception(), false);
_CATCH_END
}
};
template <class... _ArgTypes> //注意对函数的返回值类型转换 void 为 int
class _Packaged_state<void(_ArgTypes...)> : public _Associated_state<int>
{
private:
function<void(_ArgTypes...)> _Fn;
public:
using _Mybase = _Associated_state<int>;
using _Mydel = typename _Mybase::_Mydel;
template <class _Fty2> // 有参构造函数
_Packaged_state(const _Fty2& _Fnarg) : _Fn(_Fnarg) {}
template <class _Fty2> // 有参构造函数
_Packaged_state(_Fty2&& _Fnarg) : _Fn(_STD forward<_Fty2>(_Fnarg)) {}
const function<void(_ArgTypes...)>& _Get_fn() { return _Fn; } // 返回左值引用
void _Call_deferred(_ArgTypes... _Args) // set deferred call
{
_TRY_BEGIN
_Fn(_STD forward<_ArgTypes>(_Args)...);
this->_Set_value(1, true); // 可见,只要函数成功执行,就存入返回值为 1
_CATCH_ALL
this->_Set_exception(_STD current_exception(), true);
_CATCH_END
}
void _Call_immediate(_ArgTypes... _Args)
{
_TRY_BEGIN
_Fn(_STD forward<_ArgTypes>(_Args)...);
this->_Set_value(1, false);
_CATCH_ALL
this->_Set_exception(_STD current_exception(), false);
_CATCH_END
}
};
//*********************************************************************************************************
// 这是 管理函数返回值的 _Associated_state<T> 的孙子类。要执行的函数是无参的 _Rx() 形式
template <class _Rx> // class for managing associated synchronous state for deferred execution from async
class _Deferred_async_state : public _Packaged_state<_Rx()> // 用于管理从异步延迟执行的关联同步状态的类
{
public:
template <class _Fty2> // 构造函数,形参是不带参数的可调用对象。
_Deferred_async_state(const _Fty2& _Fnarg) : _Packaged_state<_Rx()>(_Fnarg) {}
template <class _Fty2> // 构造函数,形参是不带参数的可调用对象。
_Deferred_async_state(_Fty2&& _Fnarg) : _Packaged_state<_Rx()>(_STD forward<_Fty2>(_Fnarg)) {}
// 指定了函数不带参数的原因在于类 _Fake_no_copy_callable_adapter<T...>
private:
// this function is considered to be deferred until it's invoked 此函数被认为是延迟的,直到它被调用
virtual bool _Has_deferred_function() override { return !this->_Running; } // 重写虚函数
virtual void _Run_deferred_function(unique_lock<mutex>& _Lock) override // run the deferred function
{
_Lock.unlock(); // 传递锁进来,是为了解锁,只有写返回值时候才需要加锁。其余时候不必要一直持有锁
_Packaged_state<_Rx()>::_Call_immediate(); // _Call_immediate 中写返回值时 _Set_value(..)会再次加锁
_Lock.lock(); // 获得锁以后再返回,保持语义的一致性;
}
};
template <class _Rx> // class for managing associated synchronous state for asynchronous execution from async
class _Task_async_state : public _Packaged_state<_Rx()> // 用于管理从异步执行的关联同步状态的类
{
private: // 这里的 task 意思是任务,更指代的是新线程
::Concurrency::task<void> _Task; // 这是一个线程对象,管理新创建的线程
public:
using _Mybase = _Packaged_state<_Rx()>; // 简写父类,同时指出包含的是不带形参的可调用对象。
// 指定了函数不带参数的原因在于类 _Fake_no_copy_callable_adapter<T...>
using _State_type = typename _Mybase::_State_type; //= _Associated_state<_Ty>中的 _Ty函数的返回值类型
template <class _Fty2> // 有参构造函数
_Task_async_state(_Fty2&& _Fnarg) : _Mybase(_STD forward<_Fty2>(_Fnarg)) // do it now
{ // lamda 表达式,创建线程任务,为本类的数据成员线程对象赋值
_Task = ::Concurrency::create_task([this]() { this->_Call_immediate(); } );
this->_Running = true; // 在构造函数中启动了新线程,来执行函数 _Call_immediate()
}
// wait for completion,封装了未知函数 task.wait(..) 函数返回值未计算出来,本对象不予以析构,一直存在
virtual void _Wait() override { _Task.wait(); }
virtual ~_Task_async_state() noexcept { _Wait(); } // 析构函数,调用了 wait 等待
// return the stored result or throw stored exception
virtual _State_type& _Get_value(bool _Get_only_once) override
{
_Task.wait(); // 函数重写,在爷爷类的同名函数里,加了 等待函数执行完毕的 wait(..)
return _Mybase::_Get_value(_Get_only_once);
}
};
//******************************************************************************************************
//*******************下面这是一段父类 _State_manager 与子类 future,子类 shared_future*********************
// 爷类 _Associated_state 与子类 _Packaged_state 与孙类 _Deferred_async_state + _Task_async_state
// 顾名思义,现在是要开始管理这些 包含了函数返回值的 state 类。
template <class _Ty>
class _State_manager
{
private:
_Associated_state<_Ty>* _Assoc_state; // 本模板类管理里一个 state 类
bool _Get_only_once; // 当 本模板 作为 future 的父类时,_Get_only_once 为 true ;
// 当 本模板 作为 shared_future 的父类时,_Get_only_once 为 false
public:
// construct with no associated asynchronous state object
_State_manager() : _Assoc_state(nullptr) { _Get_only_once = false; } // 默认构造函数
// construct with _New_state
_State_manager(_Associated_state<_Ty>* _New_state, bool _Get_once) // 有参构造函数
: _Assoc_state(_New_state) {
_Get_only_once = _Get_once;
}
// template <class _Ty> //用于管理关联同步状态的类
// class _Associated_state
// { void _Release() { if (_MT_DECR(_Refs) == 0) _Delete_this(); } };
~_State_manager() { if (_Assoc_state) _Assoc_state->_Release(); } // 析构函数
// copy stored associated asynchronous state object from _Other 从“其他”复制存储的关联异步状态对象
void _Copy_from(const _State_manager& _Other) // 感觉核心代码就是增加了一个引用计数
{
if (this != _STD addressof(_Other)) // 本函数服务于 copy 构造函数与 copy 赋值运算符函数
{
if (_Assoc_state) _Assoc_state->_Release(); // 释放本类原来管理的函数返回值
if (_Other._Assoc_state) // do the copy
{
_Other._Assoc_state->_Retain();
// class _Associated_state { void _Retain(){ _MT_INCR(_Refs); } }; //增加引用计数
_Assoc_state = _Other._Assoc_state;
_Get_only_once = _Other._Get_only_once;
}
else
_Assoc_state = nullptr;
}
}
_State_manager(const _State_manager& _Other, bool _Get_once = false) // copy 构造函数
: _Assoc_state(nullptr) {
_Copy_from(_Other); _Get_only_once = _Get_once;
}
_State_manager& operator=(const _State_manager& _Other) { _Copy_from(_Other); return *this; }
void _Move_from(_State_manager& _Other) // 服务于 move 构造函数与 move 赋值运算符函数
{
if (this != _STD addressof(_Other))
{
if (_Assoc_state) _Assoc_state->_Release(); // 释放本类原来管理的函数返回值
_Assoc_state = _Other._Assoc_state;
_Other._Assoc_state = nullptr;
_Get_only_once = _Other._Get_only_once;
}
}
_State_manager(_State_manager&& _Other, bool _Get_once = false) // 移动构造函数
: _Assoc_state(nullptr) {
_Move_from(_Other); _Get_only_once = _Get_once;
}
_State_manager& operator=(_State_manager&& _Other) { _Move_from(_Other); return *this; }
// abandon shared state 这是出错时候的逻辑,本函数用的应该不多。正常情况下线程不会出错。故略
void _Abandon() { if (_Assoc_state) _Assoc_state->_Abandon(); }
// exchange with _Other
void _Swap(_State_manager& _Other) { _STD swap(_Assoc_state, _Other._Assoc_state); }
_Associated_state<_Ty>* _Ptr() const { return _Assoc_state; } // 返回本类保存的裸指针成员
//*********以下是各种成员功能函数*****
bool _Is_ready() const { return _Assoc_state && _Assoc_state->_Is_ready(); }
/*
class _Associated_state // 爷爷类,本注释服务于附近的三个成员函数
{
int _Ready; bool _Ready_at_thread_exit; bool _Retrieved;
bool _Is_ready() const { return _Ready != 0; }
bool _Is_ready_at_thread_exit() const { return _Ready_at_thread_exit; }
bool _Already_retrieved() const { return _Retrieved; }
};
*/
bool _Is_ready_at_thread_exit() const
{
return _Assoc_state && _Assoc_state->_Is_ready_at_thread_exit();
}
// 如经 future 读取,_Get_only_once 为 true ,只要读过一次,就不让读了
// 如经 shared_future 读取,_Get_only_once 为 false ,则本 valid() 始终返 true,表可多次读取
bool valid() const noexcept // 表本类管理的函数的返回值是否有效可读,是则返回 true
{
return _Assoc_state && !(_Get_only_once && _Assoc_state->_Already_retrieved());
}
_Ty& _Get_value() const // 获得对 _Associated_state<_Ty> 中保存的函数返回值的左值引用
{
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
return _Assoc_state->_Get_value(_Get_only_once);
}
void _Set_value(const _Ty& _Val, bool _Defer) // copy 函数的返回值
{
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
/*
template <class _Ty>
class _Associated_state //用于管理关联同步状态的类
{
// store a result while inside a locked block
void _Set_value_raw(const _Ty& _Val, unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Result = _Val;
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_value(const _Ty& _Val, bool _At_thread_exit) // store a result
{
unique_lock<mutex> _Lock(_Mtx);
_Set_value_raw(_Val, &_Lock, _At_thread_exit);
}
};
*/
_Assoc_state->_Set_value(_Val, _Defer);
}
// 从这里可以看出:_Packaged_state<T> 内封装的函数执行完后,可以设置函数的返回值;
// 但 future<T> 除了可以读取函数的返回值,也有此 set_value(..) 成员函数可以直接设置一个函数返回值
void _Set_value(_Ty&& _Val, bool _Defer) // 移动函数的返回值
{
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
/*
template <class _Ty>
class _Associated_state //用于管理关联同步状态的类
{
// store a result while inside a locked block
void _Set_value_raw(_Ty&& _Val, unique_lock<mutex>* _Lock, bool _At_thread_exit)
{
if (_Has_stored_result)
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_Result = _STD forward<_Ty>(_Val);
_Do_notify(_Lock, _At_thread_exit);
}
void _Set_value(_Ty&& _Val, bool _At_thread_exit) // store a result
{
unique_lock<mutex> _Lock(_Mtx);
_Set_value_raw(_STD forward<_Ty>(_Val), &_Lock, _At_thread_exit);
}
};
*/
_Assoc_state->_Set_value(_STD forward<_Ty>(_Val), _Defer);
}
void _Set_exception(exception_ptr _Exc, bool _Defer) //异常处理用的不多
{
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
_Assoc_state->_Set_exception(_Exc, _Defer);
}
//********以下是关于等待*******
void wait() const // wait for signal
{
if (!valid()) // valid() 定义就在上面
_Throw_future_error(make_error_code(future_errc::no_state));
/*
template <class _Ty>
class _Associated_state //用于管理关联同步状态的类
{
virtual void _Wait() // wait for signal
{
unique_lock<mutex> _Lock(_Mtx);
// 传递锁进来,是为了解锁,只有写返回值时候才需要加锁。其余时候不必要一直持有锁
_Maybe_run_deferred_function(_Lock);
while (!_Ready) _Cond.wait(_Lock);
}
};
*/
_Assoc_state->_Wait();
}
template <class _Rep, class _Per> // wait for duration
future_status wait_for(const chrono::duration<_Rep, _Per>& _Rel_time) const
{
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
/*
// names for timed wait function returns
enum class future_status { ready, timeout, deferred };
template <class _Ty>
class _Associated_state //用于管理关联同步状态的类
{
template <class _Rep, class _Per> // wait for duration
future_status _Wait_for(const chrono::duration<_Rep, _Per>& _Rel_time)
{
unique_lock<mutex> _Lock(_Mtx);
if (_Has_deferred_function())
return future_status::deferred;
if (_Cond.wait_for(_Lock, _Rel_time, _Test_ready(this)))
return future_status::ready;
return future_status::timeout;
}
};*/
return _Assoc_state->_Wait_for(_Rel_time);
}
template <class _Clock, class _Dur> // wait until time point
future_status wait_until(const chrono::time_point<_Clock, _Dur>& _Abs_time) const
{
#if _HAS_CXX20
static_assert(chrono::is_clock_v<_Clock>, "Clock type required");
#endif // _HAS_CXX20
if (!valid())
_Throw_future_error(make_error_code(future_errc::no_state));
/*
template <class _Ty>
class _Associated_state //用于管理关联同步状态的类
{
template <class _Clock, class _Dur> // wait until time point
future_status _Wait_until(const chrono::time_point<_Clock, _Dur>& _Abs_time)
{
unique_lock<mutex> _Lock(_Mtx);
if (_Has_deferred_function()) // 注释在上面的函数里
return future_status::deferred;
if (_Cond.wait_until(_Lock, _Abs_time, _Test_ready(this)))
return future_status::ready;
return future_status::timeout;
}
};
*/
return _Assoc_state->_Wait_until(_Abs_time);
}
};
//*********************************************************************************************************
struct _Nil {}; // empty struct, for unused argument types,标志类,构成函数的重载
template <class _Ty> // 类型的多次声明,在定义的前面,就有代码要引用
class shared_future;
// template <class _Ty>
// class _State_manager { _Associated_state<_Ty>* _Assoc_state; bool _Get_only_once; };
template <class _Ty> // class that defines a non-copyable asynchronous return object that holds a value
class future : public _State_manager<_Ty> // 类的实例,该实例定义了一个不可复制的异步返回对象,该对象保存一个
{
using _Mybase = _State_manager<_Ty>; // 简化父类名称
public:
/*
template <class>
bool is_reference_v = false; // determine whether type argument is a reference
template <class _Ty>
bool is_reference_v<_Ty&> = true;
template <class _Ty>
bool is_reference_v<_Ty&&> = true;
//--------------------------------------------------------------------
template <class>
bool is_const_v = false; // determine whether type argument is const qualified
template <class _Ty> // 若类型被 const 修饰,则为 true 。但也有编译器规定的例外情形
bool is_const_v<const _Ty> = true; // 函数类型和引用类型就是被 const 修饰,也是 False
//-----------------------------------------------------------------
// only function types and reference types can't be const qualified
template <class _Ty>
bool is_function_v = !is_const_v<const _Ty> && !is_reference_v<_Ty>;
template <class _Ty> // 这就排除了函数类型与引用类型,又非 void ,即为所谓的对象类型
bool is_object_v = is_const_v<const _Ty> && !is_void_v<_Ty>;
template <class _Ty> // 经测试,函数类型与 void 返回 F,其余类型还有引用都返回 T
bool is_destructible_v = __is_destructible(_Ty);
*/
// 此行判断,要求 _Ty 非数组类型,非函数类型,非引用类型,非 void;且可析构
// 这个判断,也是为了区分本模板的特化类型。函数的返回值是引用或 void 时,由本模板的特化版本处理。
static_assert(!is_array_v<_Ty>&& is_object_v<_Ty>&& is_destructible_v<_Ty>,
"T in future<T> must meet the Cpp17Destructible requirements (N4878 [futures.unique.future]/4).");
future() noexcept {} // 默认的构造函数
future(const future&) = delete; // 本 future 的 copy 构造与赋值运算符函数是禁止的,
future& operator=(const future&) = delete; // 但其父类 _State_manager 的 copy 运算是允许的
// 由 futrue 管理的 _State_manager . _Get_only_once 都为 true
// 本函数算是非典型 copy 的有参构造函数
future(const _Mybase& _State, _Nil) : _Mybase(_State, true) {}
future(future&& _Other) : _Mybase(_STD move(_Other), true) {} // 移动构造函数
future& operator=(future&& _Right) noexcept // 移动赋值运算符
{
_Mybase::operator=(_STD move(_Right));
return *this;
}
~future() noexcept {} // 析构函数,无特殊的含义
/*
template <class _Ty>
class _State_manager
{
_Associated_state<_Ty>* _Assoc_state; bool _Get_only_once;
~_State_manager() { if (_Assoc_state) _Assoc_state->_Release(); }
_Ty& _Get_value() { return _Assoc_state->_Get_value(_Get_only_once); }
};
*/
_Ty get() // block until ready then return the stored result or throw the stored exception
{ // 块直到就绪,然后返回存储的结果或抛出存储的异常
future _Local{ _STD move(*this) }; // 先把自己移动掉,包含的指针将为空, local 将是完好的
// 这么做的目的是为了析构 future ,只读取一次数据
return _STD move(_Local._Get_value());
}
/*
template <class _Ty>
class shared_future : public _State_manager<_Ty>
{
using _Mybase = _State_manager<_Ty>; // 简写父类名称
shared_future(future<_Ty>&& _Other) : _Mybase(_STD forward<_Mybase>(_Other)) {}
};
*/
shared_future<_Ty> share() { return shared_future<_Ty>(_STD move(*this)); }
};
// class that defines a non-copyable asynchronous return object that holds a reference
template <class _Ty> //类的实例,该实例定义了一个不可复制的异步返回对象,该对象保存一个引用
class future<_Ty&> : public _State_manager<_Ty*> // 当 future 的模板参数是引用时,采用此特化版本
{
using _Mybase = _State_manager<_Ty*>;
public:
future() noexcept {}
future(const future&) = delete;
future& operator=(const future&) = delete;
future(const _Mybase& _State, _Nil) : _Mybase(_State, true) {}
future(future&& _Other) noexcept : _Mybase(_STD move(_Other), true) {}
future& operator=(future&& _Right) { _Mybase::operator=(_STD move(_Right)); return *this; }
~future() noexcept {}
_Ty& get() // block until ready then return the stored result or throw the stored exception
{ // 块直到就绪,然后返回存储的结果或抛出存储的异常
future _Local{ _STD move(*this) };
return *_Local._Get_value();
}
shared_future<_Ty&> share() { return shared_future<_Ty&>(_STD move(*this)); }
};
template <> // class that defines a non-copyable asynchronous return object that does not hold a value
class future<void> : public _State_manager<int> // 定义不保存值的不可复制异步返回对象的
{
using _Mybase = _State_manager<int>;
public:
future() noexcept {}
future(const future&) = delete;
future& operator=(const future&) = delete;
// struct _Nil {}; // empty struct, for unused argument types
future(const _Mybase& _State, _Nil) : _Mybase(_State, true) {}
future(future&& _Other) noexcept : _Mybase(_STD move(_Other), true) {}
future& operator=(future&& _Right) { _Mybase::operator=(_STD move(_Right)); return *this; }
~future() noexcept {}
void get() { future _Local{ _STD move(*this) }; _Local._Get_value(); }
shared_future<void> share() { return shared_future<void>(_STD move(*this)); }
};
//********************************又一 _State_manager<_Ty> 的子类************************************
template <class _Ty> // class that defines a copyable asynchronous return object that holds a value
class shared_future : public _State_manager<_Ty> // 类的实例,它定义了一个可复制的异步返回对象,该对象保存一个值
{
using _Mybase = _State_manager<_Ty>;
public:
static_assert(!is_array_v<_Ty>&& is_object_v<_Ty>&& is_destructible_v<_Ty>,
"T in shared_future<T> must meet the Cpp17Destructible requirements (N4878 [futures.shared.future]/4).");
shared_future() noexcept {} // 默认构造函数
// 接收了一个 future 的右值引用,本类的有参构造函数
// 全局函数 forward 就是无脑给模板形参 _Mybase 加上俩 & 成为: _Mybase&& ,此处就是右值引用
shared_future(future<_Ty>&& _Other) noexcept : _Mybase(_STD forward<_Mybase>(_Other)) {}
shared_future(const shared_future& _Other) : _Mybase(_Other) {} // copy 构造函数,父类是允许 copy 的
shared_future& operator=(const shared_future& _Right) noexcept // copy 赋值运算符函数
{
_Mybase::operator=(_Right);
return *this;
}
shared_future(shared_future&& _Other) : _Mybase(_STD move(_Other)) {} // 移动构造函数
shared_future& operator=(shared_future&& _Right) noexcept // 移动赋值运算符函数
{
_Mybase::operator=(_STD move(_Right));
return *this;
}
~shared_future() noexcept {} // 也是空的析构函数
/*
template <class _Ty>
class _State_manager
{
_Associated_state<_Ty>* _Assoc_state; bool _Get_only_once;
~_State_manager() { if (_Assoc_state) _Assoc_state->_Release(); }
_Ty& _Get_value() { return _Assoc_state->_Get_value(_Get_only_once); }
};
*/
const _Ty& get() { return this->_Get_value(); }
// 注意:本成员函数的返回值是函数返回值的左值引用。故没有函数返回值的副本
};
template <class _Ty> // class that defines a copyable asynchronous return object that holds a reference
class shared_future<_Ty&> : public _State_manager<_Ty*>
{
using _Mybase = _State_manager<_Ty*>;
public:
shared_future() noexcept {}
shared_future(future<_Ty&>&& _Other) noexcept : _Mybase(_STD forward<_Mybase>(_Other)) {}
shared_future(const shared_future& _Other) noexcept : _Mybase(_Other) {}
shared_future& operator=(const shared_future& _Right) noexcept
{
_Mybase::operator=(_Right);
return *this;
}
shared_future(shared_future&& _Other) noexcept : _Mybase(_STD move(_Other)) {}
shared_future& operator=(shared_future&& _Right) noexcept
{
_Mybase::operator=(_STD move(_Right));
return *this;
}
~shared_future() noexcept {}
_Ty& get() const
{
// block until ready then return the stored result or throw the stored exception
return *this->_Get_value();
}
};
template <> // class that defines a copyable asynchronous return object that does not hold a value
class shared_future<void> : public _State_manager<int>
{
using _Mybase = _State_manager<int>;
public:
shared_future() noexcept {}
shared_future(future<void>&& _Other) noexcept : _Mybase(_STD forward<_Mybase>(_Other)) {}
shared_future(const shared_future& _Other) noexcept : _Mybase(_Other) {}
shared_future& operator=(const shared_future& _Right) noexcept
{
_Mybase::operator=(_Right);
return *this;
}
shared_future(shared_future&& _Other) noexcept : _Mybase(_STD move(_Other)) {}
shared_future& operator=(shared_future&& _Right)
{
_Mybase::operator=(_STD move(_Right));
return *this;
}
~shared_future() noexcept {}
void get() const // block until ready then return or throw the stored exception
{
this->_Get_value();
}
};
//******************************_Promise 则是含有 _State_manager 成员**************************************
template <class _Ty> // 注意前导的下划线 _Promise
class _Promise
{
private:
// _State_manager<T> { _Associated_state<T>* _Assoc_state; bool _Get_only_once; };
_State_manager<_Ty> _State; // 该类也有子类,future 与 share_future,但本 _Promise 没有使用
bool _Future_retrieved; // 函数的返回值是否已交给 future 管理,初始化为 false,后改为 true
public:
_Promise(_Associated_state<_Ty>* _State_ptr) // 有参构造函数
: _State(_State_ptr, false), _Future_retrieved(false) {}
_Promise(const _Promise&) = delete; // 禁止 copy 构造函数
_Promise& operator=(const _Promise&) = delete; // 禁止 copy 赋值运算符函数
_Promise(_Promise&& _Other) // 移动构造函数
: _State(_STD move(_Other._State)), _Future_retrieved(_Other._Future_retrieved) {}
_Promise& operator=(_Promise&& _Other) // 移动赋值运算符函数
{
_State = _STD move(_Other._State);
_Future_retrieved = _Other._Future_retrieved;
return *this;
}
// _State_manager<T> { ~_State_manager() { if (_Assoc_state) _Assoc_state->_Release(); } };
~_Promise() noexcept {} // 空的析构函数
bool _Is_valid() { return _State.valid(); }
/*
_State_manager<T>
{
~_State_manager() { if (_Assoc_state) _Assoc_state->_Release(); }
bool valid() { return _Assoc_state && !( _Get_only_once && _Assoc_state->_Retrieved ); }
bool _Is_ready() { return _Assoc_state && _Assoc_state->_Is_ready(); }
bool _Is_ready_at_thread_exit() { return _Assoc_state && _Assoc_state->_Ready_at_thread_exit; }
};
*/
bool _Is_ready() { return _State._Is_ready(); } // 这几个简单的函数采用了集中注释
bool _Is_ready_at_thread_exit() { return _State._Is_ready_at_thread_exit(); }
void _Swap(_Promise& _Other)
{
_State._Swap(_Other._State);
_STD swap(_Future_retrieved, _Other._Future_retrieved);
}
const _State_manager<_Ty>& _Get_state() const { return _State; } // 注意:返回的是左值引用
_State_manager<_Ty>& _Get_state() { return _State; } // 返回结果是左值引用
_State_manager<_Ty>& _Get_state_for_set() // 返回结果是左值引用
{
if (!_State.valid()) // 给出本类的数据成员 _State_manager<_Ty> 是为了设置函数返回值
_Throw_future_error(make_error_code(future_errc::no_state));
return _State;
}
_State_manager<_Ty>& _Get_state_for_future() // 返回结果是左值引用
{
if (!_State.valid())
_Throw_future_error(make_error_code(future_errc::no_state));
if (_Future_retrieved)
_Throw_future_error(make_error_code(future_errc::future_already_retrieved));
_Future_retrieved = true; // 给 future 后,就不能再通过本 _Promise 使用函数返回值
return _State;
}
};
//********************************************************************************************************
// 模板参数 _Fty 就是 _Fake_no_copy_callable_adapter<T...> 类型,该类型的对象是可调用对象;
template <class _Ret, class _Fty> // 模板参数 _Fty 的对象其实是一个包含被调函数及其实参的 tuple 元组
_Associated_state<typename _P_arg_type<_Ret>::type>* // 返回值 // 为启动类型构造关联的异步状态对象
_Get_associated_state(launch _Psync, _Fty&& _Fnarg) // construct associated asynchronous state object for the launch type
{
switch (_Psync) // select launch type
{
case launch::deferred : // 这个 _Ret 是函数的返回结果,可以是值,引用或者为 void ,重载般的选择一个父类 _Packaged_state
return new _Deferred_async_state<_Ret>(_STD forward<_Fty>(_Fnarg)); // 这是爷爷 _Associated_state 的孙类
case launch::async : // TRANSITION, fixed in vMajorNext, should create a new thread here
default: // 注意,默认态下也将创建新线程
return new _Task_async_state<_Ret>(_STD forward<_Fty>(_Fnarg)); // 这也是爷爷 _Associated_state 的孙类
}
}
//**************************************************************************************************************
template <class... _Types, size_t... _Indices> // invoke() a tuple with explicit parameter ordering
auto _Invoke_stored_explicit(tuple<_Types...>&& _Tuple, index_sequence<_Indices...>)
-> decltype(_STD invoke(_STD get<_Indices>(_STD move(_Tuple))...))
{
return _STD invoke(_STD get<_Indices>(_STD move(_Tuple))...);
}
// 系统定义的 全局 invoke() 函数,有一个强大的功能,就是可以识别出其形参分别是可调用的函数与其参数,
// invoke() 可以把其所有的参数,整合成一个完成的函数再次运行起来。
template <class... _Types>
auto _Invoke_stored(tuple<_Types...>&& _Tuple) // invoke() a tuple
-> decltype(_Invoke_stored_explicit(_STD move(_Tuple), index_sequence_for<_Types...>{}))
{
return _Invoke_stored_explicit(_STD move(_Tuple), index_sequence_for<_Types...>{});
}
template <class... _Types> // 本类型是一个可调用对象,定义了 括号( )运算符函数
class _Fake_no_copy_callable_adapter // 核心是包括了一个 tuple 元组
{
private:
using _Storaget = tuple<decay_t<_Types>...>; // 使用了 tuple 元组
mutable _Storaget _Storage;
public:
explicit _Fake_no_copy_callable_adapter(_Types&&... _Vals) // 有参构造函数
: _Storage(_STD forward<_Types>(_Vals)...) {}
_Fake_no_copy_callable_adapter(const _Fake_no_copy_callable_adapter& _Other) // copy 构造函数
: _Storage(_STD move(_Other._Storage)) { _STD terminate(); } // Very Bad Things
_Fake_no_copy_callable_adapter(_Fake_no_copy_callable_adapter&& _Other) = default; // 默认移动构造函数
//禁止 copy赋值运算符函数 与 移动赋值运算符函数
_Fake_no_copy_callable_adapter& operator=(const _Fake_no_copy_callable_adapter&) = delete;
_Fake_no_copy_callable_adapter& operator=(_Fake_no_copy_callable_adapter&&) = delete;
auto operator()() -> decltype(_Invoke_stored(_STD move(_STD declval<_Storaget&>())))
{ // 定义了没有参数的括号 () 运算符函数
return _Invoke_stored(_STD move(_Storage)); // 看意思是返回形参中函数的返回值
}
};
//******************************************************************************************************
template <class _Fret> // type for functions returning T,本模板处理函数的返回值类型
struct _P_arg_type { using type = _Fret; };
template <class _Fret> // type for functions returning reference to T
struct _P_arg_type<_Fret&> { using type = _Fret*; };
template <> // type for functions returning void
struct _P_arg_type<void> { using type = int; };
//********************************
template <class _Fty, class... _ArgTypes> // future<T>、future<T&>、future<void> 等
future<_Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>> // 函数返回值 // 管理使用提供的策略启动的可调用对象
async(launch _Policy, _Fty&& _Fnarg, _ArgTypes&&... _Args) // manages a callable object launched with supplied policy
{
using _Ret = _Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>; // 简写函数的返回值类型
using _Ptype = typename _P_arg_type<_Ret>::type; // 对在线程中执行的函数的返回值的类型进行必要的转换
_Promise<_Ptype> _Pr(_Get_associated_state<_Ret>(_Policy,
_Fake_no_copy_callable_adapter<_Fty, _ArgTypes...>(_STD forward<_Fty>(_Fnarg), _STD forward<_ArgTypes>(_Args)...)
));
/*
_State_manager<Ty> { _Associated_state<Ty>* _Assoc_state; bool _Get_only_once; };
template <class _Ty> // 注意前导的下划线 _Promise
class _Promise
{
_State_manager<_Ty> _State; bool _Future_retrieved; // 函数的返回值是否已交给 future 管理
_Promise(_Associated_state<_Ty>* _State_ptr) // 有参构造函数
: _State(_State_ptr, false), _Future_retrieved(false) {}
// 给 future 后,就不能再通过本 _Promise 使用函数返回值 // 返回结果是左值引用
_State_manager<_Ty>& _Get_state_for_future() { _Future_retrieved = true; return _State; }
};
template <class _Ty>
class future : public _State_manager<_Ty>
{
using _Mybase = _State_manager<_Ty>;
future(const _Mybase& _State, _Nil) : _Mybase(_State, true) {}
};
*/
return future<_Ret>(_Pr._Get_state_for_future(), _Nil()); // 调用了 future 的某版本的构造函数
}
template <class _Fty, class... _ArgTypes> // 推导结果就是 future< 函数返回值 >
future<_Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>> // 管理使用默认策略启动的可调用对象
async(_Fty&& _Fnarg, _ArgTypes&&... _Args) // manages a callable object launched启动 with default policy
{
return _STD async( launch::async | launch::deferred,
_STD forward<_Fty>(_Fnarg), _STD forward<_ArgTypes>(_Args)...);
}
/*
template <class _Rx> // 本类是 _Associated_state<T> 的孙子类
class _Deferred_async_state : public _Packaged_state<_Rx()>
{
virtual void _Run_deferred_function(unique_lock<mutex>& _Lock) override { // 虚函数重写
_Lock.unlock();
_Packaged_state<_Rx()>::_Call_immediate();
_Lock.lock();
}
};
*/
/*
template <class _Ty>
class _Associated_state
{ public: using _State_type = _Ty;
_Ty _Result ; mutex _Mtx; condition_variable _Cond;
bool _Retrieved; int _Ready; bool _Running ;
virtual void _Run_deferred_function(unique_lock<mutex>&) {} // do nothing 由子类重写这个函数
void _Maybe_run_deferred_function(unique_lock<mutex>& _Lock) {
if (!_Running) { _Running = true; _Run_deferred_function(_Lock); }
}
virtual _Ty& _Get_value(bool _Get_only_once) {
unique_lock<mutex> _Lock(_Mtx);
if (_Get_only_once && _Retrieved)
_Throw_future_error(make_error_code(future_errc::future_already_retrieved));
_Retrieved = true;
_Maybe_run_deferred_function(_Lock);
while (!_Ready) _Cond.wait(_Lock);
return _Result;
}
virtual void _Wait() {
unique_lock<mutex> _Lock(_Mtx);
_Maybe_run_deferred_function(_Lock); // 执行线程中的函数,以得到返回值
while (!_Ready) _Cond.wait(_Lock); // 循环,直到函数的返回值被准备好
}
};
*/
/*
template <class _Ty>
class _State_manager // future设置 _Get_only_once 为 true
{
_Associated_state<_Ty>* _Assoc_state; bool _Get_only_once;
void wait() { _Assoc_state->_Wait(); } // future<T> 的父类定义了 wait() 成员函数
_Ty& _Get_value() { return _Assoc_state->_Get_value(_Get_only_once); }
};
template <class _Ty> // future<T> 管理的函数返回值只可以被读取一次的原因就在于使用了对象移动构造函数
class future : public _State_manager<_Ty> //futrue管理的 _State_manager._Get_only_once 都为 true
{
future(const _Mybase& _State, _Nil) : _Mybase(_State, true) {}
_Ty get() { future _Local{ _STD move(*this) }; return _STD move(_Local._Get_value()); }
};
// 以上简化代码是对 defer_async_state 的获取函数返回值的执行分析,
// 因没有创建新线程,须由 future<T>.get() 或 future<T>.wait() 驱动来获得函数返回值。
*/
// 以上简化代码是对 defer_async_state 的获取函数返回值的执行分析,
// 因没有创建新线程,须由 future<T>.get() 或 future<T>.wait() 驱动来获得函数返回值。
/**/
/*
template <class _Ret, class... _ArgTypes> // 只摘取一个重载特化版本
class _Packaged_state<_Ret(_ArgTypes...)> : public _Associated_state<_Ret>
{
function<_Ret(_ArgTypes...)> _Fn; // 传递来的 _Fake_no_copy_callable_adapter 是可调用对象
template <class _Fty2> // 采用的是这个万能引用的版本
_Packaged_state(_Fty2&& _Fnarg) : _Fn(_STD forward<_Fty2>(_Fnarg)) {}
void _Call_immediate(_ArgTypes... _Args) // call function object
{
_TRY_BEGIN // 但根据上下文 args... 是空的
this->_Set_value(_Fn(_STD forward<_ArgTypes>(_Args)...), false);
_CATCH_ALL
this->_Set_exception(_STD current_exception(), false);
_CATCH_END
}
};
template <class _Rx>
class _Task_async_state : public _Packaged_state<_Rx()>
{
::Concurrency::task<void> _Task ; // 这是一个线程,见 并发库摘录.cpp
using _Mybase = _Packaged_state<_Rx()>;
template <class _Fty2>
_Task_async_state(_Fty2&& _Fnarg) : _Mybase(_STD forward<_Fty2>(_Fnarg))
{
_Task = ::Concurrency::create_task([this]() { this->_Call_immediate(); });
this->_Running = true;
}
};
*/
// 以上注释是对 async 执行拿到函数返回值的执行流程概述补充
//***********************************************************************************************************
// 本 packaged_task<T> 模板类仅仅借助 _Packaged_state<T>、_State_manager<P>和future<P>、_Promise<P> 来完成定义;
// 类 _Deferred_async_state<R> 和 _Task_async_state<R> 只由全局 async(..) 函数使用。本模板不予以使用。
template <class> // 模板类的泛化版本,因不使用,所以只有声明,没有定义
class packaged_task; // not defined
// class that defines an asynchronous provider that returns the result of a call to a function object
// 类的实例,该实例定义了一个异步提供程序,该提供程序返回函数对象调用的结果
template <class _Ret, class... _ArgTypes> // 顾名思义,打包任务,打包将在线程中执行的函数,以保存函数返回值
class packaged_task<_Ret(_ArgTypes...)> // 看起来此模板类的特化版本要求模板参数是函数类型
{
public:
using _Ptype = typename _P_arg_type<_Ret>::type; // 转换一下函数的返回值类型:改引用为指针,该 void 为int
// class _State_manager<_Ty> { _Associated_state<_Ty>* _Assoc_state; bool _Get_only_once; };
using _MyStateManagerType = _State_manager<_Ptype>; // 简写类型
// class _Promise<_Ty> { _State_manager<_Ty> _State; bool _Future_retrieved; };
using _MyPromiseType = _Promise<_Ptype>; // 简写类型
// class _Packaged_state<_Ret& (_ArgTypes...)> : public _Associated_state<_Ret*>
using _MyStateType = _Packaged_state<_Ret(_ArgTypes...)>; // 父类 _Packaged_state 级别已内含有函数对象
private:
_MyPromiseType _MyPromise ; // 本模板类和 async(..) 函数一样,内建了 _Promise<_P> 对象
public:
packaged_task() noexcept : _MyPromise(0) {} // 默认构造函数
template <class _Fty2, enable_if_t< // 有参构造函数,要求形参是可调用对象
!is_same_v<_Remove_cvref_t<_Fty2>, packaged_task>, int> = 0> explicit
packaged_task(_Fty2&& _Fnarg) : _MyPromise(new _MyStateType(_STD forward<_Fty2>(_Fnarg))) {}
/*
class _Associated_state { exception_ptr _Exception;
void _Abandon() // 本函的语义可能是当没计算出函数返回值时,本对象就被析构释放,
{ // 则设置 _Associated_state<T>._Exception 成员,以记录此异常情况。
unique_lock<mutex> _Lock(_Mtx);
// 经测试本函代码的完整执行,仍是正常情况,不会导致进程出错退出。
if (!_Has_stored_result) {
future_error _Fut(make_error_code(future_errc::broken_promise));
_Set_exception_raw(_STD make_exception_ptr(_Fut), &_Lock, false); }
}
};
class _State_manager { _Associated_state<_Ty>* _Assoc_state;
void _Abandon() { if (_Assoc_state) _Assoc_state->_Abandon(); } };
class _Promise { _State_manager<_Ty> _State; _State_manager<_Ty>& _Get_state() { return _State; } };
*/
~packaged_task() noexcept { _MyPromise._Get_state()._Abandon(); } // 析构函数
// 说明本 packaged_task<R(A...)> 对象可以像函数一样被调用,且可以接收随时传递的参数
void operator()(_ArgTypes... _Args)
{
// class _Promise { bool _Is_ready() { return _State._Assoc_state->_Ready != 0 ; } };
if (_MyPromise._Is_ready()) // 上面是简化版的代码,求函数返回值前 ...state<R> 不能已存有返回值
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
// class _Promise { _State_manager<_Ty>& _Get_state_for_set() { return _State; } };
_MyStateManagerType& _State = _MyPromise._Get_state_for_set(); // 注意:接收值是个左值引用!!
// class _State_manager { _Associated_state<_Ty>* _Ptr() { return _Assoc_state; } };
_MyStateType* _Ptr = static_cast<_MyStateType*>(_State._Ptr()); //把函数返回的爷指针转化为爹指针
_Ptr->_Call_immediate(_STD forward<_ArgTypes>(_Args)...);
/*
template <class _Ret, class... _ArgTypes>
class _Packaged_state<_Ret& (_ArgTypes...)> : public _Associated_state<_Ret*> {
function<_Ret& (_ArgTypes...)> _Fn;
void _Call_immediate(_ArgTypes... _Args) // 实参 false 是 notify_At_thread_exit 的意思
{ this->_Set_value(_STD addressof(_Fn(_STD forward<_ArgTypes>(_Args)...)), false); }
void _Call_deferred(_ArgTypes... _Args)
{ this->_Set_value(_STD addressof(_Fn(_STD forward<_ArgTypes>(_Args)...)), true ); }
};
*/
}
//也是执行本模板封装的函数,但是是调用 _Packaged_state<T> 中的 _Call_deferred 而非 _Call_immediate
void make_ready_at_thread_exit(_ArgTypes... _Args)
{
if (_MyPromise._Is_ready())
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_MyStateManagerType& _State = _MyPromise._Get_state_for_set();
if (_State._Ptr()->_Already_has_stored_result())
_Throw_future_error(make_error_code(future_errc::promise_already_satisfied));
_MyStateType* _Ptr = static_cast<_MyStateType*>(_State._Ptr());
_Ptr->_Call_deferred(_STD forward<_ArgTypes>(_Args)...); // 只有这一行不同于 ()运算符函数
}
packaged_task(const packaged_task&) = delete; // 禁止 copy 构造函数
packaged_task& operator=(const packaged_task&) = delete; // 禁止了 copy 赋值运算符
// class _Promise { _State_manager<_Ty> _State; bool _Future_retrieved; } 移动这俩数据成员即可
packaged_task(packaged_task&& _Other) // 移动构造函数
: _MyPromise(_STD move(_Other._MyPromise)) {}
packaged_task& operator=(packaged_task&& _Other) // 移动赋值运算符函数
{
_MyPromise = _STD move(_Other._MyPromise); return *this;
}
void swap(packaged_task& _Other) { _STD swap(_MyPromise, _Other._MyPromise); }
// class _State_manager { _Associated_state<_Ty>* _Assoc_state; bool _Get_only_once;
// bool valid() { return _Assoc_state && !(_Get_only_once && _Assoc_state->_retrieved ); } };
bool valid() { return _MyPromise._Is_valid(); }
// class _Promise { _State_manager<_Ty> _State; bool _Future_retrieved;
// _State_manager<_Ty>& _Get_state_for_future() { _Future_retrieved = true; return _State; } };
future<_Ret> get_future()
{ return future<_Ret>(_MyPromise._Get_state_for_future(), _Nil()); }
// 此函数含义是 本 packaged_task 管理的函数对象只可以执行一次,函数执行结果存储在 _Associated_state 中;
// 但若想重新运行管理的函数,就释放堆区的 _Packaged_state<T> 对象,再分配一个新的 _Packaged_state<T> 对象 。
void reset() // reset to newly constructed state
{
_MyStateManagerType& _State = _MyPromise._Get_state_for_set();
_MyStateType* _MyState = static_cast<_MyStateType*>(_State._Ptr()); // 爷指针转换为爹指针
// class _Packaged_state<_Ret& (_ArgTypes...)> : public _Associated_state<_Ret*>
// { function<_Ret& (_ArgTypes...)> _Fn; };
function<_Ret(_ArgTypes...)> _Fnarg = _MyState->_Get_fn(); // 重新生成 function 对象
_MyPromiseType _New_promise(new _MyStateType(_Fnarg)); // 这非指针,这是一个数据对象
_MyPromise._Get_state()._Abandon(); // 此局部变量 _New_promise 会在函数退出时析构,
_MyPromise._Swap(_New_promise); // 同时也就回收了堆区中旧的 _Packaged_state 对象
}
};
//**********************************************************************************************************
template <class _Alloc>
struct _Allocator_deleter
{
_Alloc _Al;
using pointer = typename allocator_traits<_Alloc>::pointer;
void operator()(pointer _Ptr) noexcept // delete the pointer
{
_Destroy_in_place(*_Ptr);
/*
template <class _Ty>
void _Destroy_in_place(_Ty& _Obj) // 对象的析构函数调用与数组中对象的批量析构
{
if (is_array_v<_Ty>) _Destroy_range(_Obj, _Obj + extent_v<_Ty>);
else _Obj.~_Ty();
}
*/
_Al.deallocate(_Ptr, 1);
}
};
// template <class _Ty, class _Dx = default_delete<_Ty>>
// class unique_ptr; 可见,对于独占型智能指针,要提供一个对象删除器
template <class _Alloc> // 本模板类的定义是独占型智能指针的简写形式
using _Unique_ptr_alloc = unique_ptr<typename _Alloc::value_type, _Allocator_deleter<_Alloc>>;
// construct an object with an allocator and return it owned by a unique_ptr
template <class _Alloc, class... _Args> // 用分配器构造一个对象并返回一个unique_ptr所拥有的对象
_Unique_ptr_alloc<_Alloc> // 这一行是函数的返回值,类型定义在上面,返回独占型智能指针
_Make_unique_alloc(_Alloc& _Al, _Args&&... _Vals)
{
_Alloc_construct_ptr<_Alloc> _Constructor{ _Al };
_Constructor._Allocate();
_Construct_in_place( *_Constructor._Ptr, _STD forward<_Args>(_Vals)...);
return _Unique_ptr_alloc<_Alloc>(_Constructor._Release(), _Allocator_deleter<_Alloc>{_Al});
}
// construct an _Associated_state object with an allocator 用分配器构造 _Associated_state 对象
template <class _Ty, class _Alloc>
_Associated_state<_Ty>* // 注意本函数的返回值即可,在堆区创建 _Associated_state<_Ty> 对象
_Make_associated_state(const _Alloc& _Al)
{
using _Delty = _State_deleter<_Ty, _Associated_state<_Ty>, _Alloc>;
using _Aldelty = _Rebind_alloc_t<_Alloc, _Delty>; //= _Alloc< _Delty > 凭经验
using _Alstate = _Rebind_alloc_t<_Alloc, _Associated_state<_Ty>>; //= _Alloc< _Associated_state<_Ty> >
_Aldelty _Del_alloc(_Al); // 产生一个删除器
_Alstate _State_alloc(_Al); // 用指定的分配器产生一个 _Associated_state<_Ty> 对象
auto _Del = _Make_unique_alloc(_Del_alloc, _Al); // _Del 和 _Res 是 unique_ptr 指针
auto _Res = _Make_unique_alloc(_State_alloc, _Unfancy(_Del.get()));
/*
template <class _Ty, class _Dx >
class unique_ptr { _Compressed_pair<_Dx, pointer> _Mypair;
pointer get() { return _Mypair._Myval2; }
pointer release() noexcept { return _STD exchange(_Mypair._Myval2, nullptr); }
};
*/
(void)_Del.release(); // ownership of _Del.get() now transferred to _Res
return _Unfancy(_Res.release()); // ownership transferred to caller
/*
template <class _Ptrty> // converts from a fancy pointer to a plain pointer
auto _Unfancy(_Ptrty _Ptr) noexcept { return _STD addressof(*_Ptr); } // 从智能指针转换为裸指针
template <class _Ty> // do nothing for plain pointers
_Ty* _Unfancy(_Ty* _Ptr) noexcept { return _Ptr; }
*/
}
//******************************************************************************************************
// _State_manager { _Associated_state<_Ty>* _Assoc_state; bool _Get_only_once ; } ;
// _State_manager<T> 对象,即是其子类 future<T>、share_future<T> 中的对象成员;
// 也是 _Promise<T> 中的数据成员,也是 promise<U>、promise<U&>、promise<void> 中的数据对象成员。
// 区别是:函 async(..) 调用时,爷指针指向孙对象;
// : packaged_task<R(a…)> 对象在 thread 线程中调用时,爷指针指向爹对象;
// : promise<M> 在线程中调用时,爷指针指向爷对象自己,仅存储一个线程安全的线程间共享的数据。
template <class _Ty> // class that defines an asynchronous provider that holds a value
class promise // 类的实例,它定义了一个异步提供程序,该提供程序保存一个值
{
private:
_Promise<_Ty> _MyPromise; // _Promise<_Ty> { _State_manager<_Ty> _State; bool _Future_retrieved; };
public:
/*
template <class>
bool is_reference_v = false; // determine whether type argument is a reference
template <class _Ty>
bool is_reference_v<_Ty&> = true;
template <class _Ty>
bool is_reference_v<_Ty&&> = true;
//--------------------------------------------------------------------
template <class>
bool is_const_v = false; // determine whether type argument is const qualified
template <class _Ty> // 若类型被 const 修饰,则为 true 。但也有编译器规定的例外情形
bool is_const_v<const _Ty> = true; // 函数类型和引用类型就是被 const 修饰,也是 False
//-----------------------------------------------------------------
// only function types and reference types can't be const qualified
template <class _Ty>
bool is_function_v = !is_const_v<const _Ty> && !is_reference_v<_Ty>;
template <class _Ty> // 这就排除了函数类型与引用类型,又非 void ,即为所谓的对象类型
bool is_object_v = is_const_v<const _Ty> && !is_void_v<_Ty>;
template <class _Ty> // 经测试,函数类型与 void 返回 F,其余类型还有引用都返回 T
bool is_destructible_v = __is_destructible(_Ty);
*/
// 此行判断,要求 _Ty 非数组类型,非函数类型,非引用类型,非 void;且可析构
// 这个判断,也是为了区分本模板的特化类型。函数的返回值是引用或 void 时,由本模板的特化版本处理。
static_assert(!is_array_v<_Ty>&& is_object_v<_Ty>&& is_destructible_v<_Ty>,
"T in promise<T> must meet the Cpp17Destructible requirements (N4878 [futures.promise]/1).");
promise() : _MyPromise(new _Associated_state<_Ty>) {} // 默认构造函数
template <class _Alloc> // 指定类对象的分配器的有参构造函数
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<_Ty>(_Al)) {}
promise(const promise&) = delete; // 禁止 copy 构造函数
promise& operator=(const promise&) = delete; // 禁止 copy 赋值运算符函数
promise(promise&& _Other) : _MyPromise(_STD move(_Other._MyPromise)) {} // 移动构造函数
promise& operator=(promise&& _Other) noexcept // 移动赋值运算符函数
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept // 析构函数。本函数的执行,不会导致进程异常退出
{ // 意思是在没有计算出函数返回值前,本 promise 对象被析构了,则在 _Associated_state<_Ty> 中记录异常情况
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) { _MyPromise._Swap(_Other._MyPromise); }
// class _Promise
// { _State_manager<_Ty>& _Get_state_for_future() { _Future_retrieved = true; return _State; } };
future<_Ty> get_future()
{
return future<_Ty>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value(const _Ty& _Val) // copy 的语义
{
_MyPromise._Get_state_for_set()._Set_value(_Val, false);
}
void set_value(_Ty&& _Val) // 移动的语义
{
_MyPromise._Get_state_for_set()._Set_value(_STD forward<_Ty>(_Val), false);
}
void set_value_at_thread_exit(const _Ty& _Val) // copy 的语义
{
_MyPromise._Get_state_for_set()._Set_value(_Val, true);
}
void set_value_at_thread_exit( _Ty&& _Val) // 移动的语义
{
_MyPromise._Get_state_for_set()._Set_value(_STD forward<_Ty>(_Val), true);
}
void set_exception(exception_ptr _Exc) // 填写 _Associated_state<T>._Exception 成员
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
template <class _Ty> // class that defines an asynchronous provider that holds a reference
class promise<_Ty&> // 类的实例,该实例定义了一个包含引用的异步提供程序
{
private:
_Promise<_Ty*> _MyPromise; // 特化模板类,转换了存储的函数风返回值类型
public:
promise() : _MyPromise(new _Associated_state<_Ty*>) {}
template <class _Alloc>
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<_Ty*>(_Al)) {}
promise(const promise&) = delete;
promise& operator=(const promise&) = delete;
promise(promise&& _Other) noexcept : _MyPromise(_STD move(_Other._MyPromise)) {}
promise& operator=(promise&& _Other) noexcept
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept
{
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) noexcept { _MyPromise._Swap(_Other._MyPromise); }
future<_Ty&> get_future()
{
return future<_Ty&>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value(_Ty& _Val)
{
_MyPromise._Get_state_for_set()._Set_value(_STD addressof(_Val), false);
}
void set_value_at_thread_exit(_Ty& _Val)
{
_MyPromise._Get_state_for_set()._Set_value(_STD addressof(_Val), true);
}
void set_exception(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
template <> // 定义不保存值的异步提供程序
class promise<void> // defines an asynchronous provider that does not hold a value
{
private:
_Promise<int> _MyPromise; // 特化模板类,转换了存储的函数风返回值类型
public:
promise() : _MyPromise(new _Associated_state<int>) {}
template <class _Alloc>
promise(allocator_arg_t, const _Alloc& _Al) : _MyPromise(_Make_associated_state<int>(_Al)) {}
promise(const promise&) = delete;
promise& operator=(const promise&) = delete;
promise(promise&& _Other) noexcept : _MyPromise(_STD move(_Other._MyPromise)) {}
promise& operator=(promise&& _Other) noexcept
{
promise(_STD move(_Other)).swap(*this);
return *this;
}
~promise() noexcept
{
if (_MyPromise._Is_valid() && !_MyPromise._Is_ready() && !_MyPromise._Is_ready_at_thread_exit())
{
// exception if destroyed before function object returns
future_error _Fut(make_error_code(future_errc::broken_promise));
_MyPromise._Get_state()._Set_exception(_STD make_exception_ptr(_Fut), false);
}
}
void swap(promise& _Other) noexcept { _MyPromise._Swap(_Other._MyPromise); }
future<void> get_future()
{
return future<void>(_MyPromise._Get_state_for_future(), _Nil());
}
void set_value()
{
_MyPromise._Get_state_for_set()._Set_value(1, false);
}
void set_value_at_thread_exit()
{
_MyPromise._Get_state_for_set()._Set_value(1, true);
}
void set_exception(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, false);
}
void set_exception_at_thread_exit(exception_ptr _Exc)
{
_MyPromise._Get_state_for_set()._Set_exception(_Exc, true);
}
};
//***********************************************************************************************************************
_STD_END
// #define _STD_END } ,在 std 命名空间里的操作结束
#pragma pop_macro("new")
// 恢复最开始隐藏的 new 宏定义,#pragma push_macro("new")
_STL_RESTORE_CLANG_WARNINGS
// 对应最开始的,此处是恢复 clang 警告
#pragma warning(pop)
// 恢复原来的警告级别 #pragma warning(push, _STL_WARNING_LEVEL)
#pragma pack(pop)
// 恢复原来的内存对齐方式 #pragma pack(push, _CRT_PACKING)
#endif // _STL_COMPILER_PREPROCESSOR,本文件在此 #if 成立时才存在
#endif // _FUTURE_
(50) 接着给出本源文件 的资源,可下载。
(51)
谢谢。至此,本关于 C++ STL 多线程的又一个头文件, 阅读结束了。愿一切都越来越好。