/* * Copyright (c) 1996 Gunther Schadow. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef CXX_SEMAPHORE_H #define CXX_SEMAPHORE_H // very simple Semaphore class, does not yet implement everything from // SYSV ipc's `sem', just the basics, explained in every book about // operationg systems. Example: // // Semaphore mutex; // // mutex.p(); // // ... critical region ... // // mutex.v(); #pragma interface #include #include #include #include #ifdef sun extern int semget(key_t key, int nsems, int semflg); extern int semctl(int semid, int semnum, int cmd, union semun arg); extern int semop(int semid, struct sembuf *sops, int nsops); #endif class Semaphore { private: int id; struct sembuf buf; public: enum op_t { P = -1, V = +1, }; enum { nowait = IPC_NOWAIT, undo = SEM_UNDO, }; Semaphore(int flag = 0); virtual ~Semaphore() { semun x; x.val = 0; semctl(id, 0, IPC_RMID, x); } int op(op_t o) { buf.sem_op = o; return semop(id, &buf, 1); } int p() { return op(P); } int v() { return op(V); } short flags(short f) { short o=buf.sem_flg; buf.sem_flg=f; return o; } short flags() { return buf.sem_flg; } int getval() { semun x; x.val = 0; return semctl(id, 0, GETVAL, x); } }; #endif