os_thread_functions.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. //Thread launching functions are adapted from boost/detail/lightweight_thread.hpp
  11. //
  12. // boost/detail/lightweight_thread.hpp
  13. //
  14. // Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
  15. // Copyright (c) 2008 Peter Dimov
  16. //
  17. // Distributed under the Boost Software License, Version 1.0.
  18. // See accompanying file LICENSE_1_0.txt or copy at
  19. // http://www.boost.org/LICENSE_1_0.txt
  20. #ifndef BOOST_INTERPROCESS_DETAIL_OS_THREAD_FUNCTIONS_HPP
  21. #define BOOST_INTERPROCESS_DETAIL_OS_THREAD_FUNCTIONS_HPP
  22. #ifndef BOOST_CONFIG_HPP
  23. # include <boost/config.hpp>
  24. #endif
  25. #
  26. #if defined(BOOST_HAS_PRAGMA_ONCE)
  27. # pragma once
  28. #endif
  29. #include <boost/interprocess/detail/config_begin.hpp>
  30. #include <boost/interprocess/detail/workaround.hpp>
  31. #include <boost/interprocess/streams/bufferstream.hpp>
  32. #include <cstddef>
  33. #include <ostream>
  34. #if defined(BOOST_INTERPROCESS_WINDOWS)
  35. # include <boost/interprocess/detail/win32_api.hpp>
  36. # include <boost/winapi/thread.hpp>
  37. #else
  38. # include <pthread.h>
  39. # include <unistd.h>
  40. # include <sched.h>
  41. # include <time.h>
  42. # ifdef BOOST_INTERPROCESS_BSD_DERIVATIVE
  43. //Some *BSD systems (OpenBSD & NetBSD) need sys/param.h before sys/sysctl.h, whereas
  44. //others (FreeBSD & Darwin) need sys/types.h
  45. # include <sys/types.h>
  46. # include <sys/param.h>
  47. # include <sys/sysctl.h>
  48. # endif
  49. #if defined(__VXWORKS__)
  50. #include <vxCpuLib.h>
  51. #endif
  52. //According to the article "C/C++ tip: How to measure elapsed real time for benchmarking"
  53. //Check MacOs first as macOS 10.12 SDK defines both CLOCK_MONOTONIC and
  54. //CLOCK_MONOTONIC_RAW and no clock_gettime.
  55. # if (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__))
  56. # include <mach/mach_time.h> // mach_absolute_time, mach_timebase_info_data_t
  57. # define BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME
  58. # elif defined(CLOCK_MONOTONIC_PRECISE) //BSD
  59. # define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC_PRECISE
  60. # elif defined(CLOCK_MONOTONIC_RAW) //Linux
  61. # define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC_RAW
  62. # elif defined(CLOCK_HIGHRES) //Solaris
  63. # define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_HIGHRES
  64. # elif defined(CLOCK_MONOTONIC) //POSIX (AIX, BSD, Linux, Solaris)
  65. # define BOOST_INTERPROCESS_CLOCK_MONOTONIC CLOCK_MONOTONIC
  66. # else
  67. # error "No high resolution steady clock in your system, please provide a patch"
  68. # endif
  69. #endif
  70. namespace boost {
  71. namespace interprocess {
  72. namespace ipcdetail{
  73. #if defined (BOOST_INTERPROCESS_WINDOWS)
  74. typedef unsigned long OS_process_id_t;
  75. typedef unsigned long OS_thread_id_t;
  76. struct OS_thread_t
  77. {
  78. OS_thread_t()
  79. : m_handle()
  80. {}
  81. void* handle() const
  82. { return m_handle; }
  83. void* m_handle;
  84. };
  85. typedef OS_thread_id_t OS_systemwide_thread_id_t;
  86. //process
  87. inline OS_process_id_t get_current_process_id()
  88. { return winapi::get_current_process_id(); }
  89. inline OS_process_id_t get_invalid_process_id()
  90. { return OS_process_id_t(0); }
  91. //thread
  92. inline OS_thread_id_t get_current_thread_id()
  93. { return winapi::get_current_thread_id(); }
  94. inline OS_thread_id_t get_invalid_thread_id()
  95. { return OS_thread_id_t(0xffffffff); }
  96. inline bool equal_thread_id(OS_thread_id_t id1, OS_thread_id_t id2)
  97. { return id1 == id2; }
  98. //return the system tick in ns
  99. inline unsigned long get_system_tick_ns()
  100. {
  101. unsigned long curres, ignore1, ignore2;
  102. winapi::query_timer_resolution(&ignore1, &ignore2, &curres);
  103. //Windows API returns the value in hundreds of ns
  104. return (curres - 1ul)*100ul;
  105. }
  106. //return the system tick in us
  107. inline unsigned long get_system_tick_us()
  108. {
  109. unsigned long curres, ignore1, ignore2;
  110. winapi::query_timer_resolution(&ignore1, &ignore2, &curres);
  111. //Windows API returns the value in hundreds of ns
  112. return (curres - 1ul)/10ul + 1ul;
  113. }
  114. typedef unsigned __int64 OS_highres_count_t;
  115. inline unsigned long get_system_tick_in_highres_counts()
  116. {
  117. __int64 freq;
  118. unsigned long curres, ignore1, ignore2;
  119. winapi::query_timer_resolution(&ignore1, &ignore2, &curres);
  120. //Frequency in counts per second
  121. if(!winapi::query_performance_frequency(&freq)){
  122. //Tick resolution in ms
  123. return (curres-1ul)/10000ul + 1ul;
  124. }
  125. else{
  126. //In femtoseconds
  127. __int64 count_fs = (1000000000000000LL - 1LL)/freq + 1LL;
  128. __int64 tick_counts = (static_cast<__int64>(curres)*100000000LL - 1LL)/count_fs + 1LL;
  129. return static_cast<unsigned long>(tick_counts);
  130. }
  131. }
  132. inline OS_highres_count_t get_current_system_highres_count()
  133. {
  134. __int64 count;
  135. if(!winapi::query_performance_counter(&count)){
  136. count = winapi::get_tick_count();
  137. }
  138. return count;
  139. }
  140. inline void zero_highres_count(OS_highres_count_t &count)
  141. { count = 0; }
  142. inline bool is_highres_count_zero(const OS_highres_count_t &count)
  143. { return count == 0; }
  144. template <class Ostream>
  145. inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count)
  146. {
  147. ostream << count;
  148. return ostream;
  149. }
  150. inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r)
  151. { return l - r; }
  152. inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r)
  153. { return l < r; }
  154. inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r)
  155. { return l < static_cast<OS_highres_count_t>(r); }
  156. inline void thread_sleep_tick()
  157. { winapi::sleep_tick(); }
  158. inline void thread_yield()
  159. { winapi::sched_yield(); }
  160. inline void thread_sleep(unsigned int ms)
  161. { winapi::sleep(ms); }
  162. //systemwide thread
  163. inline OS_systemwide_thread_id_t get_current_systemwide_thread_id()
  164. {
  165. return get_current_thread_id();
  166. }
  167. inline void systemwide_thread_id_copy
  168. (const volatile OS_systemwide_thread_id_t &from, volatile OS_systemwide_thread_id_t &to)
  169. {
  170. to = from;
  171. }
  172. inline bool equal_systemwide_thread_id(const OS_systemwide_thread_id_t &id1, const OS_systemwide_thread_id_t &id2)
  173. {
  174. return equal_thread_id(id1, id2);
  175. }
  176. inline OS_systemwide_thread_id_t get_invalid_systemwide_thread_id()
  177. {
  178. return get_invalid_thread_id();
  179. }
  180. inline long double get_current_process_creation_time()
  181. {
  182. winapi::interprocess_filetime CreationTime, ExitTime, KernelTime, UserTime;
  183. winapi::get_process_times
  184. ( winapi::get_current_process(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
  185. typedef long double ldouble_t;
  186. const ldouble_t resolution = (100.0l/1000000000.0l);
  187. return CreationTime.dwHighDateTime*(ldouble_t(1u<<31u)*2.0l*resolution) +
  188. CreationTime.dwLowDateTime*resolution;
  189. }
  190. inline unsigned int get_num_cores()
  191. {
  192. winapi::interprocess_system_info sysinfo;
  193. winapi::get_system_info( &sysinfo );
  194. //in Windows dw is long which is equal in bits to int
  195. return static_cast<unsigned>(sysinfo.dwNumberOfProcessors);
  196. }
  197. #else //#if defined (BOOST_INTERPROCESS_WINDOWS)
  198. typedef pthread_t OS_thread_t;
  199. typedef pthread_t OS_thread_id_t;
  200. typedef pid_t OS_process_id_t;
  201. struct OS_systemwide_thread_id_t
  202. {
  203. OS_systemwide_thread_id_t()
  204. : pid(), tid()
  205. {}
  206. OS_systemwide_thread_id_t(pid_t p, pthread_t t)
  207. : pid(p), tid(t)
  208. {}
  209. OS_systemwide_thread_id_t(const OS_systemwide_thread_id_t &x)
  210. : pid(x.pid), tid(x.tid)
  211. {}
  212. OS_systemwide_thread_id_t(const volatile OS_systemwide_thread_id_t &x)
  213. : pid(x.pid), tid(x.tid)
  214. {}
  215. OS_systemwide_thread_id_t & operator=(const OS_systemwide_thread_id_t &x)
  216. { pid = x.pid; tid = x.tid; return *this; }
  217. OS_systemwide_thread_id_t & operator=(const volatile OS_systemwide_thread_id_t &x)
  218. { pid = x.pid; tid = x.tid; return *this; }
  219. void operator=(const OS_systemwide_thread_id_t &x) volatile
  220. { pid = x.pid; tid = x.tid; }
  221. pid_t pid;
  222. pthread_t tid;
  223. };
  224. inline void systemwide_thread_id_copy
  225. (const volatile OS_systemwide_thread_id_t &from, volatile OS_systemwide_thread_id_t &to)
  226. {
  227. to.pid = from.pid;
  228. to.tid = from.tid;
  229. }
  230. //process
  231. inline OS_process_id_t get_current_process_id()
  232. { return ::getpid(); }
  233. inline OS_process_id_t get_invalid_process_id()
  234. { return pid_t(0); }
  235. //thread
  236. inline OS_thread_id_t get_current_thread_id()
  237. { return ::pthread_self(); }
  238. inline OS_thread_id_t get_invalid_thread_id()
  239. {
  240. static pthread_t invalid_id;
  241. return invalid_id;
  242. }
  243. inline bool equal_thread_id(OS_thread_id_t id1, OS_thread_id_t id2)
  244. { return 0 != pthread_equal(id1, id2); }
  245. inline void thread_yield()
  246. { ::sched_yield(); }
  247. #ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME
  248. typedef struct timespec OS_highres_count_t;
  249. #else
  250. typedef unsigned long long OS_highres_count_t;
  251. #endif
  252. inline unsigned long get_system_tick_ns()
  253. {
  254. #ifdef _SC_CLK_TCK
  255. long ticks_per_second =::sysconf(_SC_CLK_TCK); // ticks per sec
  256. if(ticks_per_second <= 0){ //Try a typical value on error
  257. ticks_per_second = 100;
  258. }
  259. return 999999999ul/static_cast<unsigned long>(ticks_per_second)+1ul;
  260. #else
  261. #error "Can't obtain system tick value for your system, please provide a patch"
  262. #endif
  263. }
  264. inline unsigned long get_system_tick_in_highres_counts()
  265. {
  266. #ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME
  267. return get_system_tick_ns();
  268. #else
  269. mach_timebase_info_data_t info;
  270. mach_timebase_info(&info);
  271. //ns
  272. return static_cast<unsigned long>
  273. (
  274. static_cast<double>(get_system_tick_ns())
  275. / (static_cast<double>(info.numer) / info.denom)
  276. );
  277. #endif
  278. }
  279. //return system ticks in us
  280. inline unsigned long get_system_tick_us()
  281. {
  282. return (get_system_tick_ns()-1)/1000ul + 1ul;
  283. }
  284. inline OS_highres_count_t get_current_system_highres_count()
  285. {
  286. #if defined(BOOST_INTERPROCESS_CLOCK_MONOTONIC)
  287. struct timespec count;
  288. ::clock_gettime(BOOST_INTERPROCESS_CLOCK_MONOTONIC, &count);
  289. return count;
  290. #elif defined(BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME)
  291. return ::mach_absolute_time();
  292. #endif
  293. }
  294. #ifndef BOOST_INTERPROCESS_MATCH_ABSOLUTE_TIME
  295. inline void zero_highres_count(OS_highres_count_t &count)
  296. { count.tv_sec = 0; count.tv_nsec = 0; }
  297. inline bool is_highres_count_zero(const OS_highres_count_t &count)
  298. { return count.tv_sec == 0 && count.tv_nsec == 0; }
  299. template <class Ostream>
  300. inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count)
  301. {
  302. ostream << count.tv_sec << "s:" << count.tv_nsec << "ns";
  303. return ostream;
  304. }
  305. inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r)
  306. {
  307. OS_highres_count_t res;
  308. if (l.tv_nsec < r.tv_nsec){
  309. res.tv_nsec = 1000000000 + l.tv_nsec - r.tv_nsec;
  310. res.tv_sec = l.tv_sec - 1 - r.tv_sec;
  311. }
  312. else{
  313. res.tv_nsec = l.tv_nsec - r.tv_nsec;
  314. res.tv_sec = l.tv_sec - r.tv_sec;
  315. }
  316. return res;
  317. }
  318. inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r)
  319. { return l.tv_sec < r.tv_sec || (l.tv_sec == r.tv_sec && l.tv_nsec < r.tv_nsec); }
  320. inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r)
  321. { return !l.tv_sec && (static_cast<unsigned long>(l.tv_nsec) < r); }
  322. #else
  323. inline void zero_highres_count(OS_highres_count_t &count)
  324. { count = 0; }
  325. inline bool is_highres_count_zero(const OS_highres_count_t &count)
  326. { return count == 0; }
  327. template <class Ostream>
  328. inline Ostream &ostream_highres_count(Ostream &ostream, const OS_highres_count_t &count)
  329. {
  330. ostream << count ;
  331. return ostream;
  332. }
  333. inline OS_highres_count_t system_highres_count_subtract(const OS_highres_count_t &l, const OS_highres_count_t &r)
  334. { return l - r; }
  335. inline bool system_highres_count_less(const OS_highres_count_t &l, const OS_highres_count_t &r)
  336. { return l < r; }
  337. inline bool system_highres_count_less_ul(const OS_highres_count_t &l, unsigned long r)
  338. { return l < static_cast<OS_highres_count_t>(r); }
  339. #endif
  340. inline void thread_sleep_tick()
  341. {
  342. struct timespec rqt;
  343. //Sleep for the half of the tick time
  344. rqt.tv_sec = 0;
  345. rqt.tv_nsec = get_system_tick_ns()/2;
  346. ::nanosleep(&rqt, 0);
  347. }
  348. inline void thread_sleep(unsigned int ms)
  349. {
  350. struct timespec rqt;
  351. rqt.tv_sec = ms/1000u;
  352. rqt.tv_nsec = (ms%1000u)*1000000u;
  353. ::nanosleep(&rqt, 0);
  354. }
  355. //systemwide thread
  356. inline OS_systemwide_thread_id_t get_current_systemwide_thread_id()
  357. {
  358. return OS_systemwide_thread_id_t(::getpid(), ::pthread_self());
  359. }
  360. inline bool equal_systemwide_thread_id(const OS_systemwide_thread_id_t &id1, const OS_systemwide_thread_id_t &id2)
  361. {
  362. return (0 != pthread_equal(id1.tid, id2.tid)) && (id1.pid == id2.pid);
  363. }
  364. inline OS_systemwide_thread_id_t get_invalid_systemwide_thread_id()
  365. {
  366. return OS_systemwide_thread_id_t(get_invalid_process_id(), get_invalid_thread_id());
  367. }
  368. inline long double get_current_process_creation_time()
  369. { return 0.0L; }
  370. inline unsigned int get_num_cores()
  371. {
  372. #ifdef _SC_NPROCESSORS_ONLN
  373. long cores = ::sysconf(_SC_NPROCESSORS_ONLN);
  374. // sysconf returns -1 if the name is invalid, the option does not exist or
  375. // does not have a definite limit.
  376. // if sysconf returns some other negative number, we have no idea
  377. // what is going on. Default to something safe.
  378. if(cores <= 0){
  379. return 1;
  380. }
  381. //Check for overflow (unlikely)
  382. else if(static_cast<unsigned long>(cores) >=
  383. static_cast<unsigned long>(static_cast<unsigned int>(-1))){
  384. return static_cast<unsigned int>(-1);
  385. }
  386. else{
  387. return static_cast<unsigned int>(cores);
  388. }
  389. #elif defined(BOOST_INTERPROCESS_BSD_DERIVATIVE) && defined(HW_NCPU)
  390. int request[2] = { CTL_HW, HW_NCPU };
  391. int num_cores;
  392. std::size_t result_len = sizeof(num_cores);
  393. if ( (::sysctl (request, 2, &num_cores, &result_len, 0, 0) < 0) || (num_cores <= 0) ){
  394. //Return a safe value
  395. return 1;
  396. }
  397. else{
  398. return static_cast<unsigned int>(num_cores);
  399. }
  400. #elif defined(__VXWORKS__)
  401. cpuset_t set = ::vxCpuEnabledGet();
  402. #ifdef __DCC__
  403. int i;
  404. for( i = 0; set; ++i)
  405. {
  406. set &= set -1;
  407. }
  408. return(i);
  409. #else
  410. return (__builtin_popcount(set) );
  411. #endif
  412. #endif
  413. }
  414. inline int thread_create(OS_thread_t * thread, void *(*start_routine)(void*), void* arg)
  415. { return pthread_create(thread, 0, start_routine, arg); }
  416. inline void thread_join(OS_thread_t thread)
  417. { (void)pthread_join(thread, 0); }
  418. #endif //#if defined (BOOST_INTERPROCESS_WINDOWS)
  419. typedef char pid_str_t[sizeof(OS_process_id_t)*3+1];
  420. inline void get_pid_str(pid_str_t &pid_str, OS_process_id_t pid)
  421. {
  422. bufferstream bstream(pid_str, sizeof(pid_str));
  423. bstream << pid << std::ends;
  424. }
  425. inline void get_pid_str(pid_str_t &pid_str)
  426. { get_pid_str(pid_str, get_current_process_id()); }
  427. #if defined(BOOST_INTERPROCESS_WINDOWS)
  428. inline int thread_create( OS_thread_t * thread, boost::ipwinapiext::LPTHREAD_START_ROUTINE_ start_routine, void* arg )
  429. {
  430. void* h = boost::ipwinapiext::CreateThread(0, 0, start_routine, arg, 0, 0);
  431. if( h != 0 ){
  432. thread->m_handle = h;
  433. return 0;
  434. }
  435. else{
  436. return 1;
  437. }
  438. }
  439. inline void thread_join( OS_thread_t thread)
  440. {
  441. winapi::wait_for_single_object( thread.handle(), winapi::infinite_time );
  442. winapi::close_handle( thread.handle() );
  443. }
  444. #endif
  445. class abstract_thread
  446. {
  447. public:
  448. virtual ~abstract_thread() {}
  449. virtual void run() = 0;
  450. };
  451. template<class T>
  452. class os_thread_func_ptr_deleter
  453. {
  454. public:
  455. explicit os_thread_func_ptr_deleter(T* p)
  456. : m_p(p)
  457. {}
  458. T *release()
  459. { T *p = m_p; m_p = 0; return p; }
  460. T *get() const
  461. { return m_p; }
  462. T *operator ->() const
  463. { return m_p; }
  464. ~os_thread_func_ptr_deleter()
  465. { delete m_p; }
  466. private:
  467. T *m_p;
  468. };
  469. #if defined(BOOST_INTERPROCESS_WINDOWS)
  470. inline boost::winapi::DWORD_ __stdcall launch_thread_routine(boost::winapi::LPVOID_ pv)
  471. {
  472. os_thread_func_ptr_deleter<abstract_thread> pt( static_cast<abstract_thread *>( pv ) );
  473. pt->run();
  474. return 0;
  475. }
  476. #else
  477. extern "C" void * launch_thread_routine( void * pv );
  478. inline void * launch_thread_routine( void * pv )
  479. {
  480. os_thread_func_ptr_deleter<abstract_thread> pt( static_cast<abstract_thread *>( pv ) );
  481. pt->run();
  482. return 0;
  483. }
  484. #endif
  485. template<class F>
  486. class launch_thread_impl
  487. : public abstract_thread
  488. {
  489. public:
  490. explicit launch_thread_impl( F f )
  491. : f_( f )
  492. {}
  493. void run()
  494. { f_(); }
  495. private:
  496. F f_;
  497. };
  498. template<class F>
  499. inline int thread_launch( OS_thread_t & pt, F f )
  500. {
  501. os_thread_func_ptr_deleter<abstract_thread> p( new launch_thread_impl<F>( f ) );
  502. int r = thread_create(&pt, launch_thread_routine, p.get());
  503. if( r == 0 ){
  504. p.release();
  505. }
  506. return r;
  507. }
  508. } //namespace ipcdetail{
  509. } //namespace interprocess {
  510. } //namespace boost {
  511. #include <boost/interprocess/detail/config_end.hpp>
  512. #endif //BOOST_INTERPROCESS_DETAIL_OS_THREAD_FUNCTIONS_HPP