[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

pthread_rwlock_wrlock cannot upgrade an existing read lock to a write lock



Some pthreads documentation mentions that
pthread_rwlock_wrlock/pthread_rwlock_trywrlock can upgrade an existing
shared read lock to a write lock, under some conditions. I am running
lenny with nptl (not sure that this is relevant), gcc 4.3.2, and
trying to figure out whether this statement about a lock upgrade
possibility is true for this environment.

>From what I see, it doesn't work,
pthread_rwlock_wrlock/pthread_rwlock_trywrlock only succeeds when the
rwlock isn't held by anyone.

The following test always fails on pthread_rwlock_trywrlock with EBUSY
status. Replacing pthread_rwlock_trywrlock with pthread_rwlock_wrlock
makes the program lock on this call.

Is this behaviour correct, or there is a problem with the read-write
locks implementation and an upgrade from read lock to a write lock
isn't possible?


Thanks,
Martin Lemke

(compile the test with -pthread)

#include <pthread.h>
#include <stdio.h>
#include <string.h>


int main (int argv, char* argc[])
{
  pthread_rwlock_t r = PTHREAD_RWLOCK_INITIALIZER;
  int ret;

  if ((ret = pthread_rwlock_rdlock (&r)) != 0)
    {
      printf ("rwlock_rdlock failed: %d\n", ret);
      return 1;
    }

  if ((ret = pthread_rwlock_trywrlock (&r)) != 0)
    {
      printf ("rwlock_trywrlock failed: %d\n", ret);
      return 1;
    }

  if ((ret = pthread_rwlock_unlock (&r)) != 0)
    {
      printf ("rwlock_unlock failed: %d\n", ret);
      return 1;
    }

  if ((ret = pthread_rwlock_unlock (&r)) != 0)
    {
      printf ("second rwlock_unlock failed: %d\n", ret);
      return 1;
   }

  return 0;
}


Reply to: