]> git.tdb.fi Git - libs/core.git/blobdiff - source/core/semaphore.cpp
New system_error exception class
[libs/core.git] / source / core / semaphore.cpp
index bba39642c8c6aee8c52da11e931555a13645d485..139cae2f4ca523ffac47af9487663799a65c17ea 100644 (file)
@@ -4,6 +4,7 @@ This file is part of libmspcore
 Copyright © 2006  Mikko Rasa, Mikkosoft Productions
 Distributed under the LGPL
 */
+
 #ifndef WIN32
 #include <sys/time.h>
 #endif
@@ -29,15 +30,36 @@ Semaphore::Semaphore(Mutex &m):
        init();
 }
 
+void Semaphore::init()
+{
+#ifdef WIN32
+       count = 0;
+       sem = CreateSemaphore(0, 0, 32, 0);
+#else
+       pthread_cond_init(&sem, 0);
+#endif
+}
+
+Semaphore::~Semaphore()
+{
+       if(own_mutex)
+               delete mutex;
+#ifdef WIN32
+       CloseHandle(sem);
+#else
+       pthread_cond_destroy(&sem);
+#endif
+}
+
 #ifdef WIN32
 int Semaphore::signal()
 {
        if(count==0) 
                return 0;
 
-       int ret=!ReleaseSemaphore(sem, 1, 0); 
+       int ret = !ReleaseSemaphore(sem, 1, 0); 
 
-       unsigned old_count=count;
+       unsigned old_count = count;
        mutex->unlock();
        while(count==old_count)
                Sleep(0);
@@ -50,7 +72,7 @@ int Semaphore::broadcast()
 {
        if(count==0)
                return 0;
-       int ret=!ReleaseSemaphore(sem, count, 0);
+       int ret = !ReleaseSemaphore(sem, count, 0);
 
        mutex->unlock();
        while(count)
@@ -64,7 +86,7 @@ int Semaphore::wait()
 { 
        ++count; 
        mutex->unlock();
-       DWORD ret=WaitForSingleObject(sem, INFINITE); 
+       DWORD ret = WaitForSingleObject(sem, INFINITE); 
        mutex->lock();
        --count;
        
@@ -75,13 +97,13 @@ int Semaphore::wait()
 int Semaphore::wait(const Time::TimeDelta &d)
 {
 #ifndef WIN32
-       Time::TimeStamp ts=Time::now()+d;
+       Time::TimeStamp ts = Time::now()+d;
 
        timespec timeout;
-       timeout.tv_sec=ts.raw()/1000000;
-       timeout.tv_nsec=(ts.raw()%1000000)*1000;
+       timeout.tv_sec = ts.raw()/1000000;
+       timeout.tv_nsec = (ts.raw()%1000000)*1000;
 
-       int r=pthread_cond_timedwait(&sem, &mutex->mutex, &timeout);
+       int r = pthread_cond_timedwait(&sem, &mutex->mutex, &timeout);
        if(r==ETIMEDOUT)
                return 1;
        else if(r)
@@ -90,32 +112,11 @@ int Semaphore::wait(const Time::TimeDelta &d)
 #else
        ++count;
        mutex->lock();
-       DWORD ret=WaitForSingleObject(sem, (DWORD)(d/Time::usec));
+       DWORD ret = WaitForSingleObject(sem, (DWORD)(d/Time::usec));
        mutex->unlock();
        --count;
        return ret==WAIT_OBJECT_0;
 #endif
 }
 
-Semaphore::~Semaphore()
-{
-       if(own_mutex)
-               delete mutex;
-#ifdef WIN32
-       CloseHandle(sem);
-#else
-       pthread_cond_destroy(&sem);
-#endif
-}
-
-void Semaphore::init()
-{
-#ifdef WIN32
-       count=0;
-       sem=CreateSemaphore(0, 0, 32, 0);
-#else
-       pthread_cond_init(&sem, 0);
-#endif
-}
-
 } // namespace Msp