Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.
2465 Discussions

TBB task_group tasks interplay with system semaphores

pei__yu
Beginner
375 Views

I have a legacy system that will use the available semaphore libraries for synchronization (windows.h/dispatch.h/semaphore.h for Windows/Mac/Linux). Now we are changing our system to have the tasks scheduled by TBB and task_group will require the least changes at the moment (we are looking at using flow graph in the future) and we want to make sure that no deadlock will be created for the current case.

From what I have read from the forums and documentation, TBB tasks are not preemptive, while OS might schedule away the worker thread, but at return the same TBB task will continue. I have the following code to test this idea with 1 scheduler thread. My question is should there be cases where I will have deadlock, if I only have one thread available? (from my runs I don't have deadlocks and switching the order of Thread 0 and 1 function have no effect)  Thanks for any clarification!

Yu

 

#include <cstdio>
#include <semaphore.h>
#include "tbb/task_group.h"
#include "tbb/task_scheduler_init.h"

using namespace std;
using namespace tbb;

/*Global task_group and semaphore */
task_group my_tbb_group;
sem_t my_sem;
int test_var = 0;

void ThreadFcn0(){
  /*
   * This thread will double the current test_var after thread 1 increments the value by 1
   */
  sem_wait(&my_sem);
  test_var *= 2;
}

void ThreadFcn1(){
  /*
   * This thread will increment the test_var and release the sempahore for Thread 0 to run
   */
  test_var += 1;
  sem_post(&my_sem);
}

int main(int argc, char* argv[]){
  /*init the semaphore to be in blocking state(0) */
  sem_init(&my_sem, 0, 0);
  task_scheduler_init init(1); /*Create n number of threads in the TBB scheduler */
  for(int i=0; i< 20; i++){
    //
    my_tbb_group.run([]{ThreadFcn1();});
    my_tbb_group.run([]{ThreadFcn0();});
    my_tbb_group.wait();
    printf("At iteration %d and current value is %d\n", i, test_var);
  }
}

 

0 Kudos
1 Reply
pei__yu
Beginner
375 Views

After further reading I found that we can use global_control to limit the threads, but even specifying that with 1, we still will get at least two. the run() interface use spawn() so this doesn't fall under the case for enqueue() exception for the number of threads (https://software.intel.com/en-us/node/589744). I guess it is safe to assume the semaphore will not cause deadlocks in any circumstances?

0 Kudos
Reply