CrystalSpace

Public API Reference

csutil/threading/pthread_condition.h

00001 /*
00002   Copyright (C) 2006 by Marten Svanfeldt
00003 
00004   This library is free software; you can redistribute it and/or
00005   modify it under the terms of the GNU Lesser General Public
00006   License as published by the Free Software Foundation; either
00007   version 2 of the License, or (at your option) any later version.
00008 
00009   This library is distributed in the hope that it will be useful,
00010   but WITHOUT ANY WARRANTY; without even the implied warranty of
00011   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012   Library General Public License for more details.
00013 
00014   You should have received a copy of the GNU Library General Public
00015   License along with this library; if not, write to the Free
00016   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
00017 */
00018 
00019 #ifndef __CS_CSUTIL_THREADING_PTHREAD_CONDITION_H__
00020 #define __CS_CSUTIL_THREADING_PTHREAD_CONDITION_H__
00021 
00022 #ifndef DOXYGEN_RUN
00023 
00024 #include "csutil/threading/atomicops.h"
00025 #include "csutil/threading/mutex.h"
00026 #include "csutil/noncopyable.h"
00027 
00028 #include <sys/time.h>
00029 
00030 namespace CS
00031 {
00032 namespace Threading
00033 {
00034 namespace Implementation
00035 {
00036 
00037   class ConditionBase
00038   {
00039   public:
00040     ConditionBase ()
00041     {
00042       pthread_cond_init (&condition, 0);
00043     }
00044 
00045     void NotifyOne ()
00046     {
00047       pthread_cond_signal (&condition);
00048     }
00049 
00050     void NotifyAll ()
00051     {
00052       pthread_cond_broadcast (&condition);
00053     }
00054 
00055     template<typename LockType>
00056     bool Wait (LockType& lock, csTicks timeout)
00057     {
00058       if (timeout > 0)
00059       {
00060         long const nsec_per_sec = 1000 * 1000 * 1000;
00061         struct timeval now;
00062         struct timespec to;
00063         gettimeofday (&now, 0);
00064         to.tv_sec = now.tv_sec + (timeout / 1000);
00065         to.tv_nsec = (now.tv_usec + (timeout % 1000) * 1000) * 1000;
00066         if (to.tv_nsec >= nsec_per_sec) // Catch overflow.
00067         {
00068           to.tv_sec += to.tv_nsec / nsec_per_sec;
00069           to.tv_nsec %= nsec_per_sec;
00070         }
00071         return pthread_cond_timedwait (&condition, &lock.mutex, &to) 
00072           == 0;
00073       }
00074       else
00075       {
00076         pthread_cond_wait (&condition, &lock.mutex);
00077         return true;
00078       }      
00079     }
00080 
00081 
00082   protected:
00083     pthread_cond_t condition;
00084   };
00085 
00086 }
00087 }
00088 }
00089 
00090 #endif // DOXYGEN_RUN
00091 
00092 #endif // __CS_CSUTIL_THREADING_PTHREAD_CONDITION_H__

Generated for Crystal Space 1.2.1 by doxygen 1.5.3