1

I have this code for swapping elements:

   atomic{
       int temp = a[i];
       a[i] =a[j];
       a[j] = temp;
  }

How would I implement this using fine-grained locking to achieve the same effect?

Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
user2035796
  • 67
  • 2
  • 7
  • 14

3 Answers3

1

You can use mutex to achieve this effect,

mutex.lock();
atomic
{
   int temp = a[i];
   a[i] =a[j];
   a[j] = temp;
}
mutex.unlock();

If there are multiple threads you can use POSIX style Read/Write locks as follows,

pthread_rwlock_rdlock(rw_lock_ptr);
atomic
{
   int temp = a[i];
   a[i] =a[j];
   a[j] = temp;
}
pthread_rwlock_unlock(rw_lock_ptr);
Deepu
  • 7,592
  • 4
  • 25
  • 47
0

In my understanding, you mean some classical explicit locking approach, such as mutexes.

That would require not only the swapping code, but also all the places where a[] is accessed, to be protected by the mutex. Otherwise you can't be sure that some other thread isn't in the process of reading from a[], as you do the swap.

Not sure 100% about the semantics of your atomic{}` block, and how that would work to protect against the same problem (just becase the swap itself happens atomically, it could still "mix" badly with code executing in a different thread and lead to problems).

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Assuming that a[i] and a[j] can be accessed by other threads, acquire a mutex whenever your code access those elements.

Claudio
  • 10,614
  • 4
  • 31
  • 71