00001 #ifndef Semaphore_CPP 00002 #define Semaphore_CPP 00003 00004 #define DEADLOCK_SEM 1000 00005 00006 static int cnt = 0; 00007 00008 #include "Semaphore.hpp" 00009 #include <iostream.h> 00010 00011 Semaphore::Semaphore( int init, const char* sem_name, int c ) 00012 : state( init ), color( c ), fg( 0 ) 00013 { 00014 name = (char*)sem_name; 00015 if ( c > 15 ) { color = c - 16; fg++; } 00016 if ( sem_name[0] == 's' ) { fg = 1; } 00017 } 00018 00019 void Semaphore::P() 00020 { 00021 m.lock(); 00022 while ( state < 1 ) 00023 { 00024 m.unlock(); 00025 if ( ++cnt > DEADLOCK_SEM ) { 00026 printf( "Deadlock(%s=%d|%d)", name, cnt, state ); fflush( stdout ); 00027 exit( 1 ); 00028 } 00029 sched_yield(); 00030 m.lock(); 00031 } 00032 --state; 00033 m.unlock(); 00034 } 00035 00036 void Semaphore::V() { 00037 m.lock(); 00038 ++state; 00039 m.unlock(); 00040 } 00041 00042 SCHAR Semaphore::get() { 00043 register SCHAR s = 0; 00044 m.lock(); 00045 s = state; 00046 m.unlock(); 00047 00048 return s; 00049 } 00050 00051 #endif