os_thread_functions.hpp 17 KB

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