Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between nested locks and simple locks

i am unable to figure out the difference between omp_nest_lock_t and omp_lock_t lck; this code perfectly synchronizes the longtask(), but on execution unable to figure out the difference between them;

  omp_nest_lock_t lck_n;          //omp_lock_t lck;
    int t_id;
    omp_init_nest_lock(&lck_n);    //omp_init_lock(&lck);
    omp_set_num_threads(6);

    #pragma omp parallel private(t_id) shared(lck_n) 
    {
    t_id = omp_get_thread_num();
    omp_set_nest_lock(&lck_n);      //omp_set_lock(&lck);
    printf("\nhi by %d\n",t_id);
    long_task();
    printf("My thread id is %d.\n", id);
   omp_unset_nest_lock(&lck_n);      //omp_unset_lock(&lck);
    }
    omp_destroy_nest_lock(&lck_n);    //omp_destroy_lock(&lck);
like image 579
puneet336 Avatar asked Mar 07 '14 08:03

puneet336


1 Answers

A nested lock can be locked several times. It doesn't unlock until you have unset it as many times as the number of calls to omp_set_nest_lock.

A simple lock should only be omp_set_lock once, and unlocks on one call to omp_unset_lock.

The purpose of having nested locks is that you can have functions that call other functions using the same lock. E.g.

class object { int number; ... }
linked_list<object&> ll;
omp_nest_lock_t ll_lock;

void add_to_linked_list(object& o)
{
    omp_set_nest_lock(ll_lock);

    ll.push_back(o);

    omp_unset_nest_lock(ll_lock);
}

void increement_or_add(object& o)
{
    omp_set_nest_lock(ll_lock);
    if (ll.find(o)) 
       o.number++;
    else 
      add_to_linked_list(o);
    omp_unset_nest_lock(ll_lock);
}

Now, this wouldn't work if you used simple locks, because setting/unsetting the lock more than once is not allowed, and we couldn't guarantee that the "add" is done atomically - thus two threads could potentially update ll with the same value at once.

(The code above is written to illustrate the situation, not necessarily as "good code").

like image 141
Mats Petersson Avatar answered Sep 23 '22 14:09

Mats Petersson