Export (0) Print
Expand All

omp_test_lock 

Attempts to set a lock but does not block thread execution.


int omp_test_lock(
   omp_lock_t *lock
);

where,

lock

A variable of type omp_lock_t that was initialized with omp_init_lock.

// omp_test_lock.cpp
// compile with: /openmp
#include <stdio.h>
#include <omp.h>
                    
omp_lock_t simple_lock;                 
                    
int main() {
    omp_init_lock(&simple_lock);
                    
    #pragma omp parallel num_threads(4)
    {
        int tid = omp_get_thread_num();

        while (!omp_test_lock(&simple_lock))
            printf_s("Thread %d - failed to acquire simple_lock\n",
                     tid);
                    
        printf_s("Thread %d - acquired simple_lock\n", tid);
                       
        printf_s("Thread %d - released simple_lock\n", tid);
        omp_unset_lock(&simple_lock);
    }
                    
    omp_destroy_lock(&simple_lock);
}

Sample Output

Thread 1 - acquired simple_lock
Thread 1 - released simple_lock
Thread 0 - failed to acquire simple_lock
Thread 3 - failed to acquire simple_lock
Thread 0 - failed to acquire simple_lock
Thread 3 - failed to acquire simple_lock
Thread 2 - acquired simple_lock
Thread 0 - failed to acquire simple_lock
Thread 3 - failed to acquire simple_lock
Thread 0 - failed to acquire simple_lock
Thread 3 - failed to acquire simple_lock
Thread 2 - released simple_lock
Thread 0 - failed to acquire simple_lock
Thread 3 - failed to acquire simple_lock
Thread 0 - acquired simple_lock
Thread 3 - failed to acquire simple_lock
Thread 0 - released simple_lock
Thread 3 - failed to acquire simple_lock
Thread 3 - acquired simple_lock
Thread 3 - released simple_lock

Community Additions

ADD
Show:
© 2014 Microsoft