Howard Hinnant | c51e102 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 1 | //===------------------------- thread.cpp----------------------------------===// |
| 2 | // |
Howard Hinnant | c566dc3 | 2010-05-11 21:36:01 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
Howard Hinnant | c51e102 | 2010-05-11 19:42:16 +0000 | [diff] [blame] | 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "thread" |
| 11 | #include "exception" |
| 12 | #include <sys/sysctl.h> |
| 13 | |
| 14 | _LIBCPP_BEGIN_NAMESPACE_STD |
| 15 | |
| 16 | thread::~thread() |
| 17 | { |
| 18 | if (__t_ != nullptr) |
| 19 | terminate(); |
| 20 | } |
| 21 | |
| 22 | void |
| 23 | thread::join() |
| 24 | { |
| 25 | int ec = pthread_join(__t_, 0); |
| 26 | if (ec) |
| 27 | throw system_error(error_code(ec, system_category()), "thread::join failed"); |
| 28 | __t_ = nullptr; |
| 29 | } |
| 30 | |
| 31 | void |
| 32 | thread::detach() |
| 33 | { |
| 34 | int ec = EINVAL; |
| 35 | if (__t_ != 0) |
| 36 | { |
| 37 | ec = pthread_detach(__t_); |
| 38 | if (ec == 0) |
| 39 | __t_ = 0; |
| 40 | } |
| 41 | if (ec) |
| 42 | throw system_error(error_code(ec, system_category()), "thread::detach failed"); |
| 43 | } |
| 44 | |
| 45 | unsigned |
| 46 | thread::hardware_concurrency() |
| 47 | { |
| 48 | int n; |
| 49 | int mib[2] = {CTL_HW, HW_NCPU}; |
| 50 | std::size_t s = sizeof(n); |
| 51 | sysctl(mib, 2, &n, &s, 0, 0); |
| 52 | return n; |
| 53 | } |
| 54 | |
| 55 | namespace this_thread |
| 56 | { |
| 57 | |
| 58 | void |
| 59 | sleep_for(const chrono::nanoseconds& ns) |
| 60 | { |
| 61 | using namespace chrono; |
| 62 | if (ns >= nanoseconds::zero()) |
| 63 | { |
| 64 | timespec ts; |
| 65 | ts.tv_sec = static_cast<decltype(ts.tv_sec)>(duration_cast<seconds>(ns).count()); |
| 66 | ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns - seconds(ts.tv_sec)).count()); |
| 67 | nanosleep(&ts, 0); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | } // this_thread |
| 72 | |
| 73 | _LIBCPP_END_NAMESPACE_STD |