Question

Today, I'm trying to make a task manager for a personnal project.

I wrote the following method :

template<class Callback, class... Args>
void ThreadManager::AddTaskToRun(Callback&& fun,     Args&&... args)
{
task_handle<function<void()>> task = make_task([&]()
{
    fun(forward<Args>(args)...);
});

/* Another code */
}

And I call it with the following sample :

void Test(int taskId)
{
wcout << "Hello " << taskId << endl;
}


threadManager.AddTaskToRun(Test, 1);
threadManager.AddTaskToRun(Test, 2);
threadManager.AddTaskToRun(Test, 3);

And

int x = 0;
threadManager.AddTaskToRun(Test, x);
x++;
threadManager.AddTaskToRun(Test, x);
x++;
threadManager.AddTaskToRun(Test, x);

The problem is that, in Debug mode (with Visual Studio 2013), I have the following result :

Hello 1 (first test)
Hello 2
Hello 3

And

Hello 2 (second test, with a variable in argument)
Hello 2
Hello 2

The second test has a big problem no? :-)

And if I test in Release mode :

Hello 3 Hello 3 Hello 3

And

Hello 2 Hello 2 Hello 2

Well. It's strange I think. I've search on the web but found nothing. I just seen that if I run my function outside the "make_task" or "create_task" (PPL), all results are good :

template<class Callback, class... Args>
void ThreadManager::AddTaskToRun(Callback&& fun,     Args&&... args)
{
fun(forward<Args>(args)...);

/* Another code */
}

Anyone have an idea to help me?

Thank you in advance

Was it helpful?

Solution

I've found the solution after several hours of test. I've search in thread.h file, and discover in their constructor _Decay_copy, and tried to use it in my method :

template<class Callback, class... Args>
void ThreadManager::AddTaskToRun(Callback&& fun,     Args&&... args)
{
task_handle<function<void(void)>> task = bind(_Decay_copy(forward<Callback>(fun)), _Decay_copy(forward<Args>(args))...);

/* Another code */
}

By using this task with task_group, it works fine.

Thank you :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top