// L-16 MCS 572 Wed 28 Sep 2016 : pipe_tbb.cpp
// This example is adapted from the reference manual, pages 55-57,
// illustrating the construction of a pipeline with the Intel
// Threading Building Blocks (TBB).
// We construct two filters, inheriting from the TBB filter class.

#include <iostream>
#include "tbb/pipeline.h"
#include "tbb/compat/thread"
#include "tbb/task_scheduler_init.h"

using namespace tbb;

int Sequence[] = {1,-2,3,-4,0}; // 0 is sentinel

class DoublingFilter: public filter
{
   int* my_ptr;
   public:
      DoublingFilter() :
         filter(serial_in_order),
         my_ptr(Sequence) {}
      void* operator()(void*)
      {
         if(*my_ptr)
         {
            *my_ptr = (*my_ptr)*2;
            return (void*)my_ptr++;
         }
         else
            return NULL;
      }
};

class OutputFilter: public thread_bound_filter
{
   public:
      OutputFilter() :
         thread_bound_filter(serial_in_order) {}
      void* operator()(void* item)
      {
         int *v = (int*)item; 
         std::cout << " " << (*v)*2;
         return NULL;
      }
};

void RunPipeline ( pipeline* p )
{
   p->run(8);
}

int main ( int argc, char* argv[] )
{
   std::cout << " the input sequence :";
   for(int* s = Sequence; *s; s++) std::cout << " " << *s;
   std::cout << "\nthe output sequence :";

   DoublingFilter f;   // construct the pipeline
   DoublingFilter g; OutputFilter h;

   pipeline p;
   p.add_filter(f); p.add_filter(g); p.add_filter(h);

   // another thread initiates execution of the pipeline
   std::thread t(RunPipeline,&p);
   // process the thread_bound_filter with the current thread.
   while (h.process_item() != thread_bound_filter::end_of_stream)
      continue;
   // wait for pipeline to finish on the other thread.
   t.join();
   std::cout << "\n";

   return 0;
}
