Home > Software design >  How do I return a value if I need to unlock a mutex after locking it?
How do I return a value if I need to unlock a mutex after locking it?

Time:10-07

I am writing a program in C where I need multiple threads to access elements in a queue. Obviously, I need to have some sort of lock in place so multiple threads aren't trying to tamper with the same element in the queue at one time.

So what I've done is create a wrapper around my queue for each thread to call instead of accessing my queue directly.

Where I am having troubles is in my dequeue command specifically. The way my dequeue command should work is that I need to return whatever data is stored at the head of the queue - however, since I am trying to make my queue atomic I must wrap my dequeue function with a lock (pthread_mutex_lock/unlock()). If I need to return that data to the calling function, how can I do so while still being able to unlock my lock?

int atomic_dequeue(Queue q) {
  pthread_mutex_lock(&lock);
  return dequeue(q);
  pthread_mutex_unlock(&lock);
}

CodePudding user response:

Store the value in a variable.

int atomic_dequeue(Queue q) {
  pthread_mutex_lock(&lock);
  int rv = dequeue(q);
  pthread_mutex_unlock(&lock);
  return rv;
}
  • Related