[c++11 concurrent Programming] 14 associated tasks and expectations

Source: Internet
Author: User

std::p ackaged_task<> will expect to bind to a function or callable object. When std::p the Ackaged_task<> object is triggered, it invokes the associated function and callable object so that the expectation is satisfied and the return value is filled in the data that is expected to be associated. This can be used to build the thread pool, or it can be used for task management (each task executes in its own thread or in the order of all tasks in a background thread). If a large operation can be split into multiple subtasks, each sub-task can be put into an std::p ackaged_task<> instance, and then hand over the instance to the Task Scheduler or thread pool. This allows the scheduler to deal with only std::p ackaged_task<> instances instead of dealing with specific functions.

std::p The template parameter of the Ackaged_task<> template class is a function signature, such as void () is a function with no input parameters and a null return value. Passed to std: the function return value of the:p ackaged_task<> also takes the amount return value of the get_future () member function. The parameter list for the function signature is used to indicate the invocation operator of the task function. std::p ackaged_task<std::string (Std::vector<char>*,int) > Part of the statement is as follows:

Template<>class packaged_task<std::string (std::vector<char>*,int) >{public:    template< TypeName callable>    Explicit Packaged_task (callable&& f);    Std::future<std::string> get_future ();    void operator () (std::vector<char>*,int);};
std::p Ackaged_task object is also a callable object that can be passed to the Std::function object, passed to the Std::thread object as a thread function, passed to another function that requires a callable object, or can be called directly. When std::p Ackaged_task is called as a function object, the arguments passed to operator () are passed to the Packaged_task function, and the return value is stored in std::future as the result of the asynchronous operation, by get_ The future () can get this result. Perform std: After:p ackaged_task, you can wait for expectations to be met when you need to perform the results.

Here is a concrete example. Many GUI frameworks need to be updated by a particular thread to complete the GUI. If another thread needs to update the GUI, it must send a message to the correct thread. STD::p Ackaged_task provides an implementation that does not require custom messages for each GUI-related behavior:

#include <iostream> #include <deque> #include <mutex> #include <future> #include <thread> #include <utility> #include <chrono>std::mutex m;std::d eque<std::p ackaged_task<void () > > tasks;static int shutdown = 3;bool gui_shutdown_message_received () {//executes 3 times then ends GUI thread return ((shutdown--) < 0);}  void Get_and_process_gui_message () {}//countdown 3 sec Void Countdown () {int from = 3, to = 0;    for (int i=from; i!=to; i.) {std::cout << i << ' \ n ';  Std::this_thread::sleep_for (Std::chrono::seconds (1)); } std::cout << "Lift off!\n";} GUI thread void Gui_thread () {//loop until the end message is received while (!gui_shutdown_message_received ()) {std::cout << gui_thread    "<< Std::endl;        Get GUI messages and process get_and_process_gui_message ();        std::p ackaged_task<void () > task;            {std::lock_guard<std::mutex> lk (m);            If there are no tasks in the queue, perform the next loop if (Tasks.empty ()) continue; From the queueGets the task Task=std::move (Tasks.front ());        Tasks.pop_front ();    }//Release mutex, execute task (); }}std::thread Gui_bg_thread (gui_thread); Template<typename func>std::future<void> Post_task_for_gui_ Thread (Func f) {std::cout << "post_task_for_gui_thread" << std::endl;//create Packaged_task, Task function Countdown std    ::p ackaged_task<void () > Task (f);    Obtain the desired std::future<void> res=task.get_future () from the task;    Std::lock_guard<std::mutex> LK (m);    Add a task to the queue Tasks.push_back (Std::move (Task)); return res;} int main () {std::cout << "main" << std::endl;std::future<void> f = post_task_for_gui_thread (countdown ); Std::cout << "posted 1" << Std::endl;post_task_for_gui_thread (Countdown); Std::cout << "posted 2"    << std::endl;//waits for the first GUI thread's task to complete f.get (); Std::cout << "got" << Std::endl; Gui_bg_thread.join ();}
Program execution effect is as follows, the main function, the creation of two Post_task_for_gui_thread objects, when the GUI thread executes, first perform a countdown task, the first Countdown task is completed, the main thread continues to execute (print got), Then perform the second countdown task.

maingui_threadpost_task_for_gui_threadposted 1post_task_for_gui_threadposted 2321Lift Off!gui_threadgot321Lift off !gui_threadgui_thread--------------------------------Process exited after 6.243 seconds with return value 0 Press any key to continue . . .
This example uses std::p ackaged_task<void () > Create a task that contains a function or callable object with no parameter and no return value (the return value is discarded if the call has a return value). This may be the simplest task, as you've seen before, std::p ackaged_task can also be used in complex situations-by specifying a different function signature as a template parameter, you can not only change its return type (so that the type of data will exist in the desired state), You can also change the parameter type of the function operator. This example can be simply extended to allow the task to run on a graphical interface thread, and accept the pass-through std::future return value, rather than just completing a flag as a task.
If some tasks cannot be represented by simple function calls, you can use the third "expectation" to resolve: Use std::p romise to display settings for values.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[c++11 concurrent programming] 14 associated tasks and expectations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.