Search code examples
copenmp

Is it possible to specify mutliple threads with OpenMP's `masked filter(1)`?


From the OpenMP 6.0 Spec Chap12.5:

The filter clause selects a SUBSET of the threads of the team that executes the binding parallel region to execute the structured block of the masked region.

But the filter()-clause seems to accept only one single integer.

So how can one specify a subset of threads which execute the associated code-block?

I would like to do sth like:

#include <omp.h>
#include <stdio.h>

int main() {
#pragma omp parallel masked filter(1,3)
    {
        printf("Hello from %d\n", omp_get_thread_num());
    }
    return 0;
}


Solution

  • #pragma omp master
    

    Was always just an alias for

    if (omp_get_thread_num() == 0)
    

    The filter clause with masked now allows you to explicitly specify the right-hand side of the equal check with a dynamic value.

    The important information is this sentence from the masked region section:

    The result of evaluating the thread_num argument of the filter clause may vary across threads.

    #pragma omp masked filter(omp_get_thread_num()/2*2)
    

    Will execute the masked region on even threads. Adding 1 selects for odd threads.

    #pragma omp masked filter(omp_get_thread_num()%5)
    

    Will execute the region on threads 0-4.

    While there is no big syntactic advantage of using the directive vs the if statement, the directive might document the intention more clearly and static analysis tools - compilers, optimizers, or correctness analysis - can build on the clear semantics of the expression.