dimanche 30 juillet 2017

Cannot Return Values When Passing Function by Reference To TBB Task

I'm getting my feet wet with Intel TBB and am trying to figure out why I cannot populate a vector passed in by reference to a TBB Task when I also pass in a function by reference.

Here is the code:

// tbbTesting.cpp : Defines the entry point for the console application.

#include "stdafx.h"

#include "tbb/task.h"

#include <functional>
#include <iostream>
#include <random>

#define NUM_POINTS 10


void myFunc(std::vector<double>& numbers)
{
   std::mt19937_64 gen;
   std::uniform_real_distribution<double> dis(0.0, 1000.0);

   for (size_t i = 0; i < NUM_POINTS; i++)
   {
      auto val = dis(gen);
      std::cout << val << std::endl; //proper values generated
      numbers.push_back(val);  //why is this failing?
   }

   std::cout << std::endl;

   for (auto i : numbers)
   {
      std::cout << numbers[i] << std::endl; //garbage values
   }
}


class TASK_generateRandomNumbers : public tbb::task
{
public:
   TASK_generateRandomNumbers(std::function<void(std::vector<double>&)>& fnc, 
std::vector<double>& nums) : _fnc(fnc), _numbers(nums) {}
   ~TASK_generateRandomNumbers() {};

   tbb::task* execute()
   {
      _fnc(_numbers);
      return nullptr;
   }

private:
   std::function<void(std::vector<double>&)>& _fnc;
   std::vector<double>& _numbers;
};


class Manager
{
public:
   Manager() { _numbers.reserve(NUM_POINTS); }
   ~Manager() {}

   void GenerateNumbers()
   {
        _fnc = std::bind(&myFunc, _numbers);
        TASK_generateRandomNumbers* t = new(tbb::task::allocate_root()) 
        TASK_generateRandomNumbers(_fnc, _numbers);
        tbb::task::spawn_root_and_wait(*t);
   }

   auto GetNumbers() const { return _numbers; }

private:
   std::function<void(std::vector<double>&)> _fnc;
   std::vector<double> _numbers;
};



int main()
{
   Manager mgr;
   mgr.GenerateNumbers();
   auto numbers = mgr.GetNumbers(); //returns empty
}

When the execute method performs the operation, I can get values when passing the vector by reference.

When the execute method has to call a function, I get garbage data printed to the console (push_back failing?) and I get an empty container on return.

Can anyone see what I'm missing? Thanks.

Aucun commentaire:

Enregistrer un commentaire