/* * Active Router Transport Protocol (ARTP) implementation * Copyright (c) 2004, Tomas Rebok * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the "BSD License" which is * distributed with the software in the file LICENSE. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD * License for more details. */ /** @file * Help macros for readers/writers problem. * @author Tomas Rebok * @date 2004 */ #ifndef ARTP_RWLOCKS_H #define ARTP_RWLOCKS_H 1 /** Initialize all necessary structures. * This macro initializes all necessary mutexes and counters. */ #define RW_INIT(x, y, z, wsem, rsem, wcount, rcount) {\ if ((pthread_mutex_init(&x, NULL) != 0)\ || (pthread_mutex_init(&y, NULL) != 0)\ || (pthread_mutex_init(&z, NULL) != 0)\ || (pthread_mutex_init(&wsem, NULL) != 0)\ || (pthread_mutex_init(&rsem, NULL) != 0))\ return E_MEMORY_FAIL;\ wcount = 0;\ rcount = 0;\ } /** Readers lock. * This macro is used for readers. There can be more than one reader * simultaneously, but first writer stops new readers till the end of the * writer(s) code. */ #define READERS_LOCK(x, y, z, wsem, rsem, wcount, rcount) {\ pthread_mutex_lock(&z);\ pthread_mutex_lock(&rsem);\ pthread_mutex_lock(&x);\ (rcount)++;\ if ((rcount) == 1)\ pthread_mutex_lock(&wsem);\ pthread_mutex_unlock(&x);\ pthread_mutex_unlock(&rsem);\ pthread_mutex_unlock(&z);\ } /** Readers unlock. * This macro unlocks previously locked readers lock. It decreases the count * of readers, too. */ #define READERS_UNLOCK(x, y, z, wsem, rsem, wcount, rcount) {\ pthread_mutex_lock(&x);\ (rcount)--;\ if ((rcount) == 0)\ pthread_mutex_unlock(&wsem);\ pthread_mutex_unlock(&x);\ } /** Writers lock. * This macro is used for writers to lock. There can be only one writer at the * moment, no readers are accepted, too. Waiting writer stops all new readers * till its end. */ #define WRITERS_LOCK(x, y, z, wsem, rsem, wcount, rcount) {\ pthread_mutex_lock(&y);\ (wcount)++;\ if ((wcount) == 1)\ pthread_mutex_lock(&rsem);\ pthread_mutex_unlock(&y);\ pthread_mutex_lock(&wsem);\ } /** Writers unlock. * This macro unlocks previously locked writers lock. It decreases the count * of writers, too. */ #define WRITERS_UNLOCK(x, y, z, wsem, rsem, wcount, rcount) {\ pthread_mutex_unlock(&wsem);\ pthread_mutex_lock(&y);\ (wcount)--;\ if ((wcount) == 0)\ pthread_mutex_unlock(&rsem);\ pthread_mutex_unlock(&y);\ } #endif /* vim: set ts=4 : */