当前位置:   article > 正文

C++11中std::packaged_task的使用_std::pagetask

std::pagetask

C++11中的std::packaged_task是个模板类。std::packaged_task包装任何可调用目标(函数、lambda表达式、bind表达式、函数对象)以便它可以被异步调用。它的返回值或抛出的异常被存储于能通过std::future对象访问的共享状态中。

std::packaged_task类似于std::function,但是会自动将其结果传递给std::future对象。

std::packaged_task对象内部包含两个元素:(1).存储的任务(stored task)是一些可调用的对象(例如函数指针、成员或函数对象的指针)( A stored task, which is some callable object (such as a function pointer, pointer to member or function object))。(2).共享状态,它可以存储调用存储的任务(stored task)的结果,并可以通过std::future进行异步访问(A shared state, which is able to store the results of calling the stored task and be accessed asynchronously through a future)。

通过调用std::packaged_task的get_future成员将共享状态与std::future对象关联。调用之后,两个对象共享相同的共享状态:(1).std::packaged_task对象是异步提供程序(asynchronous provider),应通过调用存储的任务(stored task)在某个时刻将共享状态设置为就绪。(2).std::future对象是一个异步返回对象,可以检索共享状态的值,并在必要时等待其准备就绪。

共享状态的生存期至少要持续到与之关联的最后一个对象释放或销毁为止。

std::packaged_task不会自己启动,你必须调用它(A packaged_task won't start on it's own, you have to invoke it)

std::future介绍参考:https://blog.csdn.net/fengbingchun/article/details/104115489

模板类std::packaged_task成员函数包括:

1. 构造函数:(1).默认构造函数:无共享状态无存储任务(no shared state and no stored task)情况下初始化对象。(2). initialization constructor:该对象具有共享状态,且其存储的任务由fn初始化。(3). initialization constructor with allocator。(4).禁用拷贝构造。(5).支持移动构造。

2. 析构函数:(1).放弃(abandon)共享状态并销毁packaged_task对象。(2). 如果有其它future对象关联到同一共享状态,则共享状态本身不会被销毁。(3). 如果packaged_task对象在共享状态准备就绪前被销毁,则共享状态自动准备就绪并包含一个std::future_error类型的异常。

3. get_future函数:(1).返回一个与packaged_task对象的共享状态关联的std::future对象。(2).一旦存储的任务被调用,返回的std::future对象就可以访问packaged_task对象在共享状态上设置的值或异常。(3).每个packaged_task共享状态只能被一个std::future对象检索(Only one future object can be retrieved for each packaged_task shared state)。(4).调用此函数后,packaged_task应在某个时候使其共享状态准备就绪(通过调用其存储的任务),否则将在销毁后自动准备就绪并包含一个std::future_error类型的异常。

4. make_ready_at_thread_exit函数:在线程退出时才使共享状态ready而不是在调用完成后就立即ready。

5. operator=:(1).禁用拷贝赋值。(2).支持移动赋值。

6. operator():(1).call stored task。(2).如果对存储任务的调用成功完成或抛出异常,则返回的值或捕获的异常存储在共享状态,共享状态准备就绪(解除阻塞当前等待它的所有线程)。

7. reset函数:(1).在保持相同存储的任务的同时,以新的共享状态重置对象。(2).允许再次调用存储的任务。(3).与对象关联的之前的共享状态被放弃(就像packaged_task被销毁了一样)。(4).在内部,该函数的行为就像是移动赋值了一个新构造的packaged_task一样(Internally, the function behaves as if move-assigned a newly constructed packaged_task (with its stored task as argument))。

8. swap函数/非成员模板函数swap:交换共享状态和存储的任务(stored task)。

9. valid函数:检查packaged_task对象是否具有共享状态。

详细用法见下面的测试代码,下面是从其他文章中copy的测试代码,部分作了调整,详细内容介绍可以参考对应的reference:

  1. #include "future.hpp"
  2. #include <iostream>
  3. #include <future>
  4. #include <chrono>
  5. #include <utility>
  6. #include <thread>
  7. #include <functional>
  8. #include <memory>
  9. #include <exception>
  10. #include <numeric>
  11. #include <vector>
  12. #include <cmath>
  13. #include <string>
  14. namespace future_ {
  15. ///
  16. // reference: http://www.cplusplus.com/reference/future/packaged_task/
  17. int test_packaged_task_1()
  18. {
  19. { // constructor/get_future/operator=/valid
  20. std::packaged_task<int(int)> foo; // default-constructed
  21. std::packaged_task<int(int)> bar([](int x) { return x * 2; }); // initialized
  22. foo = std::move(bar); // move-assignment
  23. std::cout << "valid: " << foo.valid() << "\n";
  24. std::future<int> ret = foo.get_future(); // get future
  25. std::thread(std::move(foo), 10).detach(); // spawn thread and call task
  26. int value = ret.get(); // wait for the task to finish and get result
  27. std::cout << "The double of 10 is " << value << ".\n";
  28. }
  29. { // reset/operator()
  30. std::packaged_task<int(int)> tsk([](int x) { return x * 3; }); // package task
  31. std::future<int> fut = tsk.get_future();
  32. tsk(33);
  33. std::cout << "The triple of 33 is " << fut.get() << ".\n";
  34. // re-use same task object:
  35. tsk.reset();
  36. fut = tsk.get_future();
  37. std::thread(std::move(tsk), 99).detach();
  38. std::cout << "Thre triple of 99 is " << fut.get() << ".\n";
  39. }
  40. { // constructor/get_future
  41. auto countdown = [](int from, int to) {
  42. for (int i = from; i != to; --i) {
  43. std::cout << i << '\n';
  44. std::this_thread::sleep_for(std::chrono::seconds(1));
  45. }
  46. std::cout << "Lift off!\n";
  47. return from - to;
  48. };
  49. std::packaged_task<int(int, int)> tsk(countdown); // set up packaged_task
  50. std::future<int> ret = tsk.get_future(); // get future
  51. std::thread th(std::move(tsk), 5, 0); // spawn thread to count down from 5 to 0
  52. int value = ret.get(); // wait for the task to finish and get result
  53. std::cout << "The countdown lasted for " << value << " seconds.\n";
  54. th.join();
  55. }
  56. return 0;
  57. }
  58. ///
  59. // reference: https://en.cppreference.com/w/cpp/thread/packaged_task
  60. int test_packaged_task_2()
  61. {
  62. { // lambda
  63. std::packaged_task<int(int, int)> task([](int a, int b) { return std::pow(a, b);});
  64. std::future<int> result = task.get_future();
  65. task(2, 9);
  66. std::cout << "task_lambda:\t" << result.get() << '\n';
  67. }
  68. { // bind
  69. std::packaged_task<int()> task(std::bind([](int x, int y) { return std::pow(x, y); }, 2, 11));
  70. std::future<int> result = task.get_future();
  71. task();
  72. std::cout << "task_bind:\t" << result.get() << '\n';
  73. }
  74. { // thread
  75. std::packaged_task<int(int, int)> task([](int x, int y) { return std::pow(x, y); });
  76. std::future<int> result = task.get_future();
  77. std::thread task_td(std::move(task), 2, 10);
  78. task_td.join();
  79. std::cout << "task_thread:\t" << result.get() << '\n';
  80. }
  81. return 0;
  82. }
  83. ///
  84. // reference: https://thispointer.com/c11-multithreading-part-10-packaged_task-example-and-tutorial/
  85. struct DBDataFetcher {
  86. std::string operator()(std::string token)
  87. {
  88. // Do some stuff to fetch the data
  89. std::string data = "Data From " + token;
  90. return data;
  91. }
  92. };
  93. int test_packaged_task_3()
  94. {
  95. // Create a packaged_task<> that encapsulated a Function Object
  96. std::packaged_task<std::string(std::string)> task(std::move(DBDataFetcher()));
  97. // Fetch the associated future<> from packaged_task<>
  98. std::future<std::string> result = task.get_future();
  99. // Pass the packaged_task to thread to run asynchronously
  100. std::thread th(std::move(task), "Arg");
  101. // Join the thread. Its blocking and returns when thread is finished.
  102. th.join();
  103. // Fetch the result of packaged_task<> i.e. value returned by getDataFromDB()
  104. std::string data = result.get();
  105. std::cout << data << std::endl;
  106. return 0;
  107. }
  108. ///
  109. // reference: https://stackoverflow.com/questions/18143661/what-is-the-difference-between-packaged-task-and-async
  110. int test_packaged_task_4()
  111. {
  112. // sleeps for one second and returns 1
  113. auto sleep = []() {
  114. std::this_thread::sleep_for(std::chrono::seconds(1));
  115. return 1;
  116. };
  117. { // std::packaged_task
  118. // >>>>> A packaged_task won't start on it's own, you have to invoke it
  119. std::packaged_task<int()> task(sleep);
  120. auto f = task.get_future();
  121. task(); // invoke the function
  122. // You have to wait until task returns. Since task calls sleep
  123. // you will have to wait at least 1 second.
  124. std::cout << "You can see this after 1 second\n";
  125. // However, f.get() will be available, since task has already finished.
  126. std::cout << f.get() << std::endl;
  127. }
  128. { // std::async
  129. // >>>>> On the other hand, std::async with launch::async will try to run the task in a different thread :
  130. auto f = std::async(std::launch::async, sleep);
  131. std::cout << "You can see this immediately!\n";
  132. // However, the value of the future will be available after sleep has finished
  133. // so f.get() can block up to 1 second.
  134. std::cout << f.get() << "This will be shown after a second!\n";
  135. }
  136. return 0;
  137. }
  138. } // namespace future_

GitHubhttps://github.com/fengbingchun/Messy_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/922425
推荐阅读
  

闽ICP备14008679号