Merge branch 'master' into scmaster
[nova-tt.git] / nova-tt / nanosleep.hpp
blob5b387a7a0f3be86d93242932dc4ae32f06eeed10
1 // cross-platform wrapper for nanosleep
2 // Copyright (C) 2009 Tim Blechmann
3 //
4 // This program is free software; you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation; either version 2 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program; see the file COPYING. If not, write to
16 // the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 // Boston, MA 02111-1307, USA.
19 /** \file nanosleep.hpp */
20 /** \namespace nova */
23 #ifndef NOVA_TT_NANOSLEEP_HPP
24 #define NOVA_TT_NANOSLEEP_HPP
26 #include <cassert>
28 #if defined(unix) || defined(__unix__) || defined(__unix)
29 # include <unistd.h>
30 #endif
32 #if (_POSIX_TIMERS - 0) >= 200112L
33 #include <time.h>
34 #endif /* _POSIX_TIMERS */
36 #include <boost/thread.hpp>
37 #include <boost/date_time/posix_time/posix_time_duration.hpp>
39 namespace nova
42 namespace detail
44 const unsigned long ns_per_s = 1000000000;
46 inline void nanosleep(unsigned long sec, unsigned long ns)
48 assert(ns < ns_per_s);
50 #if _POSIX_C_SOURCE >= 199309L
51 struct timespec timeout, remain;
52 timeout.tv_sec = sec;
53 timeout.tv_nsec = ns;
54 nanosleep(&timeout, &remain);
55 #else
56 #ifdef BOOST_DATE_TIME_HAS_NANOSECONDS
57 boost::this_thread::sleep(boost::posix_time::seconds(sec) + boost::posix_time::nanoseconds(ns));
58 #else
59 boost::this_thread::sleep(boost::posix_time::seconds(sec) + boost::posix_time::microseconds(ns*0.001));
60 #endif
61 #endif
64 } /* namespace detail */
66 /** sleep for ns nanoseconds
68 inline void nanosleep(unsigned long ns)
70 if (ns < detail::ns_per_s)
71 detail::nanosleep(0, ns);
72 else
73 detail::nanosleep(ns/detail::ns_per_s, ns%detail::ns_per_s);
76 } /* namespace nova */
78 #endif /* NOVA_TT_NANOSLEEP_HPP */