Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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).

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top