Download alg source code

shared readers := 0
shared readers_mutex := semaphore(1)
shared can_access := semaphore(1)

main:
  while true:
    case read_char() of:
      'R': create_thread(reader)
      'W': create_thread(writer)
      EOF: return

// WRRW

reader:
  wait(readers_mutex)
  if ++readers = 1 then
    wait(can_access)
  signal(readers_mutex)
  read()
  wait(readers_mutex)
  if --readers = 0 then
    signal(can_access);
  signal(readers_mutex)

writer:
  wait(can_access)
  write()
  signal(can_access)