/*******************************************************************************
+
+  LEDA 3.5
+
+  _thread.c
+
+  This file is part of the LEDA research version (LEDA-R) that can be 
+  used free of charge in academic research and teaching. Any commercial
+  use of this software requires a license which is distributed by the
+  LEDA Software GmbH, Postfach 151101, 66041 Saarbruecken, FRG
+  (fax +49 681 31104).
+
+  Copyright (c) 1991-1997  by  Max-Planck-Institut fuer Informatik
+  Im Stadtwald, 66123 Saarbruecken, Germany     
+  All rights reserved.
+ 
*******************************************************************************/
#include <LEDA/thread.h>

#if !defined(MULTI_THREAD)
#include <LEDA/thread/guard.h>
#include <LEDA/thread/lock.h>
#include <LEDA/thread/semaphore.h>
#endif


//rw_lock

void rw_lock::acquire_write() {

  helplock.acquire();
  lock1.acquire();
  lock2.acquire();
  helplock.release();
}

void rw_lock::release_write() {
  
  lock1.release();
  lock2.release();
}

void rw_lock::acquire_read() {

  helplock.acquire();
  lock2.acquire();
  number++;
  lock1.trylock();
  lock2.release();
  helplock.release();
}

void rw_lock::release_read() {
  lock2.acquire();
  number--;
  if (number == 0)
    lock1.release();
  lock2.release();
}


// semaphore


int semaphore::acquire() {

  int available;
 
  aclock.acquire();
  numlock.acquire();
  available = (number < maxnr_);
  numlock.release();
  if (!available)
    semalock.acquire();
  numlock.acquire();
  semalock.trylock();
  int retvalue=number;
  number++;
  numlock.release();
  aclock.release();
  return retvalue;
}

void semaphore::release() {

  numlock.acquire();
  if (number == maxnr_)
    semalock.release();
  number--;
  numlock.release();
}
