blob: 4a7904dc5423ae5409b0af7ed8027cfd6da15d01 [file] [log] [blame]
Howard Hinnantc51e1022010-05-11 19:42:16 +00001//===------------------------- thread.cpp----------------------------------===//
2//
Howard Hinnantc566dc32010-05-11 21:36:01 +00003// The LLVM Compiler Infrastructure
Howard Hinnantc51e1022010-05-11 19:42:16 +00004//
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
16thread::~thread()
17{
18 if (__t_ != nullptr)
19 terminate();
20}
21
22void
23thread::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
31void
32thread::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
45unsigned
46thread::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
55namespace this_thread
56{
57
58void
59sleep_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