Saturday 10 August 2013

Threading Building Blocks (Intel® TBB) - Hello World

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

      //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. */

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

      cout<<"In someFunction "<<i<<endl;
      //*** 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.  

No comments:

Post a Comment