Binary tree count using OpenMP threads

57 views Asked by At

This is code that counts number of elements in binary tree. I tried to understand the code but I can't. I don't understand how left_count and right_count are incremented when we didn't set them to be incremented anywhere. I also don't understand the part that it is calculated if the level is lower than 5. In the description it says that it is due to optimizations, but how do I understand it if the tree is higher than 5 levels then it will only count up to the fifth element? I'm stuck, I would appreciate the help :D

template<typename T>
void countNodes(Node<T>* head, int* result, int level = 0) {
    int left_count = 0;
    int right_count = 0;

    if (!head) {
        *result = 0;
        return;
    }

    #pragma omp parallel if(level == 0) shared(left_count, right_count) num_threads(8)
    {
        #pragma omp single nowait
        {
            #pragma omp task shared(left_count) if(level < 5)
            countNodes(head->l, &left_count, level + 1);
            #pragma omp task shared(right_count) if(level < 5)
            countNodes(head->d, &right_count, level + 1);
        }
        #pragma omp barrier
        #pragma omp single 
        *result = 1 + left_count + right_count;
    }
}
0

There are 0 answers