How to tell C ++ concurrency runtime to reuse previous thread to continue task

I used the visual C ++ concurrency environment to create a task and then scheduled four for it to continue

#include <iostream>
#include <thread>
#include <ppltasks.h>

int main()
{
    concurrency::create_task([]
    {
        std::cout << std::this_thread::get_id() << std::endl;
    })
    .then([]
    {
        std::cout << std::this_thread::get_id() << std::endl;
    })
    .then([]
    {
        std::cout << std::this_thread::get_id() << std::endl;
    })
    .then([]
    {
        std::cout << std::this_thread::get_id() << std::endl;
    })
    .then([]
    {
        std::cout << std::this_thread::get_id() << std::endl;
    });

    std::cin.get();
}

      

Will print the following output

29432
29432
25096
25668
42488

      

Note that the 4 sequels are not scheduled on the same thread as the original task. Is there a way to schedule a continuation on the same thread as the original task? I believe this is possible in C # with TaskContinuationOptions.ExecuteSynchronously .

+3


source to share


1 answer


You can usually control the context in which continuations are made with task_continuation_context

, as described in the MSDN documentation . However, the same documentation also mentions that:

It is only useful to use this class from a Windows Store app. For non-Windows Store applications, the execution context of the task continuation is determined by the runtime and is not configurable.



It seems from your code snippet that when using the Concurrency runtime, you are not using it from a Windows Store app. Therefore, the context will always always be arbitrary.

It also begs the question why you want to explicitly run subsequent tasks in the same thread as the first task: why not just put the code for those tasks inside the first task? The continuation point must return to a specific thread to continue the work done in the background job, that is, the first task will definitely be background work that you want to do, and the continuations respond to this work from the main, initiating thread. If you want to stay on the background thread, then stay there and don't bother with continuing this work. (However, as mentioned above, since this is not a Windows Store app, all these continuations and tasks run in an arbitrary context, and the runtime just picks a convenient thread.)

0


source







All Articles