Saturday 10 August 2013

Threading Building Blocks (Intel® TBB) - Hello World

#include<iostream>
#include"/tbb/mutex.h"
#include"/tbb/tbb_thread.h"
using namespace std;
using namespace tbb;

typedef mutex myMutex;
static myMutex sm;
int i=0;

void someFunction()
{
      myMutex::scoped_lock lock;//create a lock
      
      // Method acquire waits until it can
      // acquire a lock on the mutex
      lock.acquire(sm);     

      //only one thread can access the lines from here...

      /*incrementing i is safe (only one thread 
      can execute the code in this scope) because
      the mutex locked above protects all lines
      of code until the lock release. */
      ++i;

      //simply creating a delay to show that no 
      //other thread can increment i until release()
      //is executed
      sleep(1);

      cout<<"In someFunction "<<i<<endl;
         
      //***...to here***
      lock.release();//releases the lock (duh!)     
}

int main()
{
   //create a thread which executes 'someFunction'

   tbb_thread my_thread1(someFunction);
   tbb_thread my_thread2(someFunction);
   tbb_thread my_thread3(someFunction);

   // This command causes the main thread 
   //(which is the 'calling-thread' in this case)
   // to wait until thread1 completes its task.  
   my_thread1.join();
   my_thread2.join();
   my_thread3.join();
}

No comments:

Post a Comment