dnxSleep.c

Go to the documentation of this file.
00001 /*--------------------------------------------------------------------------
00002  
00003    Copyright (c) 2006-2007, Intellectual Reserve, Inc. All rights reserved.
00004  
00005    This program is free software; you can redistribute it and/or modify
00006    it under the terms of the GNU General Public License version 2 as 
00007    published by the Free Software Foundation.
00008  
00009    This program 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
00012    GNU General Public License for more details.
00013  
00014    You should have received a copy of the GNU General Public License
00015    along with this program; if not, write to the Free Software
00016    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00017  
00018   --------------------------------------------------------------------------*/
00019 
00032 #include "dnxSleep.h"
00033 
00034 #include <errno.h>
00035 #include <string.h>
00036 #include <time.h>
00037 
00038 #if HAVE_CONFIG_H
00039 # include "config.h"
00040 # ifndef HAVE_NANOSLEEP
00041 #  include <sys/time.h>
00042 #  include <pthread.h>
00043 # endif
00044 #endif
00045 
00046 /*--------------------------------------------------------------------------
00047                                  INTERFACE
00048   --------------------------------------------------------------------------*/
00049 
00050 void dnxCancelableSleep(int msecs)
00051 {
00052 #if HAVE_NANOSLEEP
00053    struct timespec rqt;
00054    rqt.tv_sec = msecs / 1000;
00055    rqt.tv_nsec = (msecs % 1000) * 1000L * 1000L;
00056    while (nanosleep(&rqt, &rqt) == -1 && errno == EINTR)
00057       ;
00058 #else
00059    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
00060    pthread_cond_t cv  = PTHREAD_COND_INITIALIZER;
00061    struct timeval now;              // time when we started waiting
00062    struct timespec timeout;         // timeout value for the wait function
00063 
00064    pthread_mutex_lock(&mutex);
00065 
00066    // timeval uses micro-seconds; timespec uses nano-seconds; 1us == 1000ns.
00067    gettimeofday(&now, 0);
00068    timeout.tv_sec = now.tv_sec + (msecs / 1000);
00069    timeout.tv_nsec = (now.tv_usec + (msecs % 1000) * 1000L) * 1000L;
00070    pthread_cond_timedwait(&cv, &mutex, &timeout);
00071 
00072    pthread_mutex_unlock(&mutex);
00073 #endif
00074 }
00075 
00076 /*--------------------------------------------------------------------------*/
00077 

Generated on Tue Apr 13 15:48:07 2010 for DNX by  doxygen 1.5.6