答疑汇总(thread,async源码分析)

简介

本文件汇总粉丝提出的关于并发的几个问题,做个备份,方便大家理解和学习。

局部变量返回值

关于局部变量返回值的问题我曾在视频中说会通过构造函数返回一个局部变量给调用者,编译器会先执行拷贝构造,如果没有拷贝构造再寻找移动构造。这么说是有问题的。
有热心的粉丝查询了chatgpt,当函数返回一个类类型的局部变量时会先调用移动构造,如果没有移动构造再调用拷贝构造。
所以对于一些没有拷贝构造但是实现了移动构造的类类型也支持通过函数返回局部变量。
在 C++11 之后,编译器会默认使用移动语义(move semantics)来提高性能

看个例子

  1. class TestCopy {
  2. public:
  3. TestCopy(){}
  4. TestCopy(const TestCopy& tp) {
  5. std::cout << "Test Copy Copy " << std::endl;
  6. }
  7. TestCopy(TestCopy&& cp) {
  8. std::cout << "Test Copy Move " << std::endl;
  9. }
  10. };
  11. TestCopy TestCp() {
  12. TestCopy tp;
  13. return tp;
  14. }

main 函数中调用TestCp

  1. int main(){
  2. TestCp();
  3. return 0;
  4. }

发现打印的是”Test Copy Move” .这说明优先调用的是移动构造,这也提醒我们,如果我们自定义的类实现了拷贝构造和移动构造,而这个类的移动给构造和拷贝构造实现方式不同时,要注意通过函数内部局部变量返回该类时调用移动构造是否会存在一些逻辑或安全的问题。

优先按照移动构造的方式返回局部的类对象,有一个好处就是可以返回一些只支持移动构造的类型

  1. std::unique_ptr<int> ReturnUniquePtr() {
  2. std::unique_ptr<int> uq_ptr = std::make_unique<int>(100);
  3. return uq_ptr;
  4. }
  5. std::thread ReturnThread() {
  6. std::thread t([]() {
  7. int i = 0;
  8. while (true) {
  9. std::cout << "i is " << i << std::endl;
  10. i++;
  11. if (i == 5) {
  12. break;
  13. }
  14. std::this_thread::sleep_for(std::chrono::seconds(1));
  15. }
  16. });
  17. return t;
  18. }

main函数中调用后,可以看到线程和unique_ptr都可被函数作为局部变量返回,而且返回的线程可以继续运行。

  1. int main(){
  2. auto rt_ptr = ReturnUniquePtr();
  3. std::cout << "rt_ptr value is " << *rt_ptr << std::endl;
  4. std::thread rt_thread = ReturnThread();
  5. rt_thread.join();
  6. return 0;
  7. }

线程归属权问题

有粉丝反馈在使用thread时遇到崩溃,主要原因在于线程归属权没有理解好,我们不能将一个线程的归属权转移给一个已经绑定线程的变量。

比如下面的调用

  1. void ThreadOp() {
  2. std::thread t1([]() {
  3. int i = 0;
  4. while (i < 5) {
  5. std::this_thread::sleep_for(std::chrono::seconds(1));
  6. i++;
  7. }
  8. });
  9. std::thread t2([]() {
  10. int i = 0;
  11. while (i < 10) {
  12. std::this_thread::sleep_for(std::chrono::seconds(1));
  13. i++;
  14. }
  15. });
  16. //不能将一个线程归属权绑定给一个已经绑定线程的变量,否则会触发terminate导致崩溃
  17. t1 = std::move(t2);
  18. t1.join();
  19. t2.join();
  20. }

我们在主函数中执行上述函数,会触发崩溃如下图

https://cdn.llfc.club/1697103423170.jpg

t1已经绑定了一个线程执行循环操作直到i<5。如果在t1没运行完的情况下将t2的归属权给t1,则会引发terminate崩溃错误。

具体原因我们可以看看thread在做移动赋值时的源码

  1. thread& operator=(thread&& _Other) noexcept {
  2. if (joinable()) {
  3. _STD terminate();
  4. }
  5. _Thr = _STD exchange(_Other._Thr, {});
  6. return *this;
  7. }

在线程joinable()返回true时,会触发terminate()操作,也就是被赋值的线程没有被join过,此时执行operator=操作会导致terminate()
至于terminate()实现比较简单

  1. _ACRTIMP __declspec(noreturn) void __cdecl terminate() throw();

可以看到terminate()就是抛出异常。

所以我们在之前的课程封装了了自动join的线程类

  1. class joining_thread {
  2. std::thread _t;
  3. public:
  4. joining_thread() noexcept = default;
  5. template<typename Callable, typename ... Args>
  6. explicit joining_thread(Callable&& func, Args&& ...args):
  7. t(std::forward<Callable>(func), std::forward<Args>(args)...){}
  8. explicit joining_thread(std::thread t) noexcept: _t(std::move(t)){}
  9. joining_thread(joining_thread&& other) noexcept: _t(std::move(other._t)){}
  10. joining_thread& operator=(joining_thread&& other) noexcept
  11. {
  12. //如果当前线程可汇合,则汇合等待线程完成再赋值
  13. if (joinable()) {
  14. join();
  15. }
  16. _t = std::move(other._t);
  17. return *this;
  18. }
  19. joining_thread& operator=(joining_thread other) noexcept
  20. {
  21. //如果当前线程可汇合,则汇合等待线程完成再赋值
  22. if (joinable()) {
  23. join();
  24. }
  25. _t = std::move(other._t);
  26. return *this;
  27. }
  28. ~joining_thread() noexcept {
  29. if (joinable()) {
  30. join();
  31. }
  32. }
  33. void swap(joining_thread& other) noexcept {
  34. _t.swap(other._t);
  35. }
  36. std::thread::id get_id() const noexcept {
  37. return _t.get_id();
  38. }
  39. bool joinable() const noexcept {
  40. return _t.joinable();
  41. }
  42. void join() {
  43. _t.join();
  44. }
  45. void detach() {
  46. _t.detach();
  47. }
  48. std::thread& as_thread() noexcept {
  49. return _t;
  50. }
  51. const std::thread& as_thread() const noexcept {
  52. return _t;
  53. }
  54. };

thread参数值拷贝

之前讲到构造std::thread对象传递回调函数和参数,回调函数的参数绑定都是值拷贝的方式,这里再梳理一次
下面是thread的构造函数

  1. template <class _Fn, class... _Args, enable_if_t<!is_same_v<_Remove_cvref_t<_Fn>, thread>, int> = 0>
  2. _NODISCARD_CTOR explicit thread(_Fn&& _Fx, _Args&&... _Ax) {
  3. _Start(_STD forward<_Fn>(_Fx), _STD forward<_Args>(_Ax)...);
  4. }

构造函数内调用了_Start函数

  1. template <class _Fn, class... _Args>
  2. void _Start(_Fn&& _Fx, _Args&&... _Ax) {
  3. // 1 处
  4. using _Tuple = tuple<decay_t<_Fn>, decay_t<_Args>...>;
  5. // 2 处
  6. auto _Decay_copied = _STD make_unique<_Tuple>(_STD forward<_Fn>(_Fx), _STD forward<_Args>(_Ax)...);
  7. // 3 处
  8. constexpr auto _Invoker_proc = _Get_invoke<_Tuple>(make_index_sequence<1 + sizeof...(_Args)>{});
  9. #pragma warning(push)
  10. #pragma warning(disable : 5039) // pointer or reference to potentially throwing function passed to
  11. // extern C function under -EHc. Undefined behavior may occur
  12. // if this function throws an exception. (/Wall)
  13. // 4处
  14. _Thr._Hnd =
  15. reinterpret_cast<void*>(_CSTD _beginthreadex(nullptr, 0, _Invoker_proc, _Decay_copied.get(), 0, &_Thr._Id));
  16. #pragma warning(pop)
  17. if (_Thr._Hnd) { // ownership transferred to the thread
  18. (void) _Decay_copied.release();
  19. } else { // failed to start thread
  20. _Thr._Id = 0;
  21. _Throw_Cpp_error(_RESOURCE_UNAVAILABLE_TRY_AGAIN);
  22. }
  23. }

我们从上面的代码 1处 可以看到_Tuple是一个去引用的类型,因为其内部存储的都是decay_t过后的类型,所以无论左值引用还是右值引用到这里都变为去引用的类型。

所以2处就是将参数和函数按照值拷贝的方式存在tuple中。

3处定义了一个可调用对象_Invoker_proc

4处启动线程调用_Invoker_proc进而调用我们传递的回调函数和参数。

所以综上所述,std::thread向回调函数传递值是以副本的方式,回调函数参数是引用类型,可以将传递的实参用std::ref包装达到修改的效果。
因为std::ref其实是构造了reference_wrapper类对象,这个类实现了仿函数

  1. _CONSTEXPR20 operator _Ty&() const noexcept {
  2. return *_Ptr;
  3. }

所以当线程接收std::ref包裹的参数时会调用仿函数通过指针解引用的方式获取外部实参,以_Ty&返回,从而达到修改的效果。

那么如下调用就会报错,提示“invoke”: 未找到匹配的重载函数。

  1. void ChangeValue() {
  2. int m = 100;
  3. std::thread t1{ [](int& rm) {
  4. rm++;
  5. }, m };
  6. t1.join();
  7. }

因为 invoke函数调用时会将参数以右值的方式移动给回调函数,这会造成左值引用绑定右值的情况,所以编译报错。

改为下面这样写就没问题了

  1. void ChangeValue() {
  2. int m = 100;
  3. std::thread t1{ [](int& rm) {
  4. rm++;
  5. }, std::ref(m) };
  6. t1.join();
  7. }

async注意事项

部分粉丝反馈async不能像js那样实现完全的纯异步,确实是存在这样的情况,因为于js不同,js是单线程的,而C++需要关注线程的生命周期。

我们使用async时,其实其内部调用了thread,pacakged_task,future等机制。async会返回一个future这个future如果会在被析构时等待其绑定的线程任务是否执行完成。

我们看一段cppreference.com中的描述

https://cdn.llfc.club/1697109536918.jpg

“The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the std::future. These methods may block if the asynchronous operation has not yet provided a value.”

异步操作async返回std::future, 调用者可以通过query,wait for等方式从std::future中查询状态。
但是如果async直接调用而不适用返回值则可能会阻塞。如下例子

  1. void BlockAsync() {
  2. std::cout << "begin block async" << std::endl;
  3. {
  4. std::async(std::launch::async, []() {
  5. std::this_thread::sleep_for(std::chrono::seconds(3));
  6. std::cout << "std::async called " << std::endl;
  7. });
  8. }
  9. std::cout << "end block async" << std::endl;
  10. }

我们在主函数调用BlockAsync(), 发现async并没有异步执行任务,而是按次序输出如下

  1. begin block async
  2. std::async called
  3. end block async

因为async返回一个右值类型的future,无论左值还是右值,future都要被析构,因为其处于一个局部作用域{}中。
当编译器执行到}时会触发future析构。但是future析构要保证其关联的任务完成,所以需要等待任务完成future才被析构,
所以也就成了串行的效果了。

所以C++ 官方文档说 如果调用析构函数的那个future是某一shared state的最后持有者,而相关的task已启动但尚未结束,析构函数会造成阻塞,直到任务结束

至于为什么future析构要等到其关联的任务完成我们可以看一下async源码

  1. template <class _Fty, class... _ArgTypes>
  2. _NODISCARD future<_Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>> async(
  3. launch _Policy, _Fty&& _Fnarg, _ArgTypes&&... _Args) {
  4. // manages a callable object launched with supplied policy
  5. using _Ret = _Invoke_result_t<decay_t<_Fty>, decay_t<_ArgTypes>...>;
  6. using _Ptype = typename _P_arg_type<_Ret>::type;
  7. //1 处
  8. _Promise<_Ptype> _Pr(
  9. _Get_associated_state<_Ret>(_Policy, _Fake_no_copy_callable_adapter<_Fty, _ArgTypes...>(
  10. _STD forward<_Fty>(_Fnarg), _STD forward<_ArgTypes>(_Args)...)));
  11. //2 处
  12. return future<_Ret>(_Pr._Get_state_for_future(), _Nil());
  13. }

我们先看看_Get_associated_state的源码

  1. template <class _Ret, class _Fty>
  2. _Associated_state<typename _P_arg_type<_Ret>::type>* _Get_associated_state(
  3. launch _Psync, _Fty&& _Fnarg) { // construct associated asynchronous state object for the launch type
  4. switch (_Psync) { // select launch type
  5. case launch::deferred:
  6. return new _Deferred_async_state<_Ret>(_STD forward<_Fty>(_Fnarg));
  7. case launch::async: // TRANSITION, fixed in vMajorNext, should create a new thread here
  8. default:
  9. return new _Task_async_state<_Ret>(_STD forward<_Fty>(_Fnarg));
  10. }
  11. }

_Get_associated_state 做的事情很简单,根据我们不同的策略deferred还是async去构造不同的异步状态。如果是launch::async策略,我们创建一个
_Task_async_state类型的指针对象,我们将这个指针转化为_Associated_state指针返回,_Associated_state_Task_async_state的基类。

async内 1处用该返回值构造了一个_Promise<_Ptype>类型的对象_Pr

async内 2处 用_Pr._Get_state_for_future()返回值构造了future,该返回值是_State_manager<_Ty>类型对象。

因为future继承于_State_manager,所以_Pr._Get_state_for_future()返回的值主要用来构造future的基类。

析构future时要析构future子类再析构其基类,future本身的析构没有什么,而其基类_State_manager<_Ty>析构时调用如下

  1. ~_State_manager() noexcept {
  2. if (_Assoc_state) {
  3. _Assoc_state->_Release();
  4. }
  5. }

看源码我们知道_Assoc_state_Associated_state<_Ty> *类型

  1. _Associated_state<_Ty>* _Assoc_state;

_Assoc_state * 就是我们之前在_Get_associated_state中开辟并返回的_Task_async_state*类型转化的。

我们沿着_Assoc_state->_Release一路追踪,会发现最终调用了下面的代码

  1. void _Delete_this() { // delete this object
  2. if (_Deleter) {
  3. _Deleter->_Delete(this);
  4. } else {
  5. delete this;
  6. }
  7. }

如果没有删除器则会直接调用delete this, 会调用_Assoc_state的析构函数,因其析构函数为虚析构,进而调用_Task_async_state的析构函数

所以我们~_State_manager()调用的其实是_Task_async_state的析构函数, 我们看一下_Task_async_state的析构函数源码

  1. virtual ~_Task_async_state() noexcept {
  2. _Wait();
  3. }
  4. virtual void _Wait() override { // wait for completion
  5. _Task.wait();
  6. }

从源码中可以看到_Task_async_state 被析构时会等待任务完成,这也就是future需等待任务完成后才析构的原因。

仅仅介绍这个事情不是我得初衷,我们介绍一种更为隐晦的死锁情况, 看下面的代码

  1. void DeadLock() {
  2. std::mutex mtx;
  3. std::cout << "DeadLock begin " << std::endl;
  4. std::lock_guard<std::mutex> dklock(mtx);
  5. {
  6. std::future<void> futures = std::async(std::launch::async, [&mtx]() {
  7. std::cout << "std::async called " << std::endl;
  8. std::lock_guard<std::mutex> dklock(mtx);
  9. std::cout << "async working...." << std::endl;
  10. });
  11. }
  12. std::cout << "DeadLock end " << std::endl;
  13. }

上面函数的作用意图在主线程中先执行加锁,再通过async启动一个线程异步执行任务,执行的任务与主线程互斥,所以在lambda表达式中加锁。
但是这么做会造成死锁,因为主线程输出”DeadLock begin “加锁,此时async启动一个线程,那么lambda表达式会先输出”std::async called “.
但是在子线程中无法加锁成功,因为主线程没有释放锁。而主线程无法释放锁,因为主线程要等待async执行完。
因为我们上面提到过,futures处于局部作用域,即将析构,而析构又要等待任务完成,任务需要加锁,所以永远完成不了,这样就死锁了。

所以使用async要注意其返回的future是不是shared state的最后持有者。

这里有个粉丝问道能不能用async实现这样的需求

  1. 你的需求是func1 中要异步执行asyncFunc函数。
  2. func2中先收集asyncFunc函数运行的结果,只有结果正确才执行
  3. func1启动异步任务后继续执行,执行完直接退出不用等到asyncFunc运行完

如果我们理解了async的原理后不难实现如下代码

  1. int asyncFunc() {
  2. std::this_thread::sleep_for(std::chrono::seconds(3));
  3. std::cout << "this is asyncFunc" << std::endl;
  4. return 0;
  5. }
  6. void func1(std::future<int>& future_ref) {
  7. std::cout << "this is func1" << std::endl;
  8. future_ref = std::async(std::launch::async, asyncFunc);
  9. }
  10. void func2(std::future<int>& future_ref) {
  11. std::cout << "this is func2" << std::endl;
  12. auto future_res = future_ref.get();
  13. if (future_res == 0) {
  14. std::cout << "get asyncFunc result success !" << std::endl;
  15. }
  16. else {
  17. std::cout << "get asyncFunc result failed !" << std::endl;
  18. return;
  19. }
  20. }
  21. //提供多种思路,这是第一种
  22. void first_method() {
  23. std::future<int> future_tmp;
  24. func1(future_tmp);
  25. func2(future_tmp);
  26. }

上面的例子我们保证在func1func2使用的是future的引用即可。这样func1内不会因为启动async而阻塞,因为future_ref不是shared state最后持有者。

如果真的想实现一个纯异步的操作倒也不难,可以这样实现

  1. template<typename Func, typename... Args >
  2. auto ParallenExe(Func&& func, Args && ... args) -> std::future<decltype(func(args...))> {
  3. typedef decltype(func(args...)) RetType;
  4. std::function<RetType()> bind_func = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
  5. std::packaged_task<RetType()> task(bind_func);
  6. auto rt_future = task.get_future();
  7. std::thread t(std::move(task));
  8. t.detach();
  9. return rt_future;
  10. }

上面的函数ParallenExe内部我们通过bind操作将函数和参数绑定,生成一个返回值为RetType类型,参数为void的函数bind_func
接着我们用这个函数生成了一个packaged_task类型的对象task,这个task获取future留作以后函数结束时返回。
我们启动了一个线程处理这个task,并将这个线程detach,保证其分离独立运行。返回的rt_future并不是shared state最后持有者,因为task内部也会持有
shared_state,引用计数并不会变为0,所以并不会触发如下析构

  1. void _Release() { // decrement reference count and destroy when zero
  2. if (_MT_DECR(_Refs) == 0) {
  3. _Delete_this();
  4. }
  5. }

那么我们写一个函数测试一下

  1. void TestParallen1() {
  2. int i = 0;
  3. std::cout << "Begin TestParallen1 ..." << std::endl;
  4. {
  5. ParallenExe([](int i) {
  6. while (i < 3) {
  7. i++;
  8. std::cout << "ParllenExe thread func " << i << " times" << std::endl;
  9. std::this_thread::sleep_for(std::chrono::seconds(1));
  10. }
  11. }, i);
  12. }
  13. std::cout << "End TestParallen1 ..." << std::endl;
  14. }

在上面的函数中我们有意让ParallenExe放在一个局部的{}中执行,意在局部作用域结束后ParallenExe返回的future引用计数-1,以此证明其引用计数是否为0,

如果引用计数为0,则会执行future的析构进而等待任务执行完成,那么看到的输出将是

  1. Begin TestParallen1 ...
  2. ParllenExe thread func 1 times
  3. ParllenExe thread func 2 times
  4. ParllenExe thread func 3 times
  5. End TestParallen1 ...

如果引用计数不会为0,则不会执行future的析构函数,那么看到的输出是这样的

  1. Begin TestParallen1 ...
  2. End TestParallen1 ...
  3. ParllenExe thread func 1 times
  4. ParllenExe thread func 2 times
  5. ParllenExe thread func 3 times

我们在main函数中调用做测试, 因为要防止主线程过早退出,所以我们先让主线程睡眠4秒

  1. int main()
  2. {
  3. TestParallen1();
  4. std::this_thread::sleep_for(std::chrono::seconds(4));
  5. std::cout << "Main Exited!\n";
  6. }

而事实证明是第二种,输出如下

  1. Begin TestParallen1 ...
  2. End TestParallen1 ...
  3. ParllenExe thread func 1 times
  4. ParllenExe thread func 2 times
  5. ParllenExe thread func 3 times

由此可见我们实现了不会阻塞的并发函数,但是也会存在一些顾虑,比如我们的主线程如果不睡眠4秒,那很可能主线程退出了子线程的任务没执行完而被强制回收。
所以归根结底,这种方式我们也需要在合适的时候等待汇合,比如调用future的get或wait操作

  1. void TestParallen2() {
  2. int i = 0;
  3. std::cout << "Begin TestParallen2 ..." << std::endl;
  4. auto rt_future = ParallenExe([](int i) {
  5. while (i < 3) {
  6. i++;
  7. std::cout << "ParllenExe thread func " << i << " times" << std::endl;
  8. std::this_thread::sleep_for(std::chrono::seconds(1));
  9. }
  10. }, i);
  11. std::cout << "End TestParallen2 ..." << std::endl;
  12. rt_future.wait();
  13. }

这就是我说的,归根结底C++和js的体系不一样,C++要管理开辟的线程生命周期,我们总归要在合适的时机汇合。
所以std::async会返回future, future会判断是不是最后持有的shared_state进而帮我们做汇合操作,这并不是缺陷而是安全性的保证。至于我们不想在该处汇合,只要保证该处future不会是最后持有shared_state的即可。

总结

本文介绍了threadasync的源码级分析,回答了大家常遇到的问题。

详细源码

https://gitee.com/secondtonone1/boostasio-learn/tree/master/concurrent/day09-QASummary

视频链接

https://space.bilibili.com/271469206/channel/collectiondetail?sid=1623290

热门评论

热门文章

  1. 解密定时器的实现细节

    喜欢(566) 浏览(2327)
  2. C++ 类的继承封装和多态

    喜欢(588) 浏览(3252)
  3. Linux环境搭建和编码

    喜欢(594) 浏览(7075)
  4. windows环境搭建和vscode配置

    喜欢(587) 浏览(1870)
  5. slice介绍和使用

    喜欢(521) 浏览(1945)

最新评论

  1. asio多线程模型IOServicePool Lion:线程池一定要继承单例模式吗
  2. 泛型算法的定制操作 secondtonone1:lambda和bind是C11新增的利器,善于利用这两个机制可以极大地提升编程安全性和效率。
  3. 类和对象 陈宇航:支持!!!!
  4. C++ 虚函数表原理和类成员内存分布 WangQi888888:class Test{ int m; int b; }中b成员是int,为什么在内存中只占了1个字节。不应该是4个字节吗?是不是int应该改为char。这样的话就会符合图上说明的情况
  5. 解决博客回复区被脚本注入的问题 secondtonone1:走到现在我忽然明白一个道理,无论工作也好生活也罢,最重要的是开心,即使一份安稳的工作不能给我带来事业上的积累也要合理的舍弃,所以我还是想去做喜欢的方向。

个人公众号

个人微信