blob: 2a6b2054eba55b1e510ad3b26cf21bdd3a58b78a [file] [log] [blame]
Howard Hinnantbc8d3f92010-05-11 19:42:16 +00001//===------------------------- thread.cpp----------------------------------===//
2//
Howard Hinnantf5256e12010-05-11 21:36:01 +00003// The LLVM Compiler Infrastructure
Howard Hinnantbc8d3f92010-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{
Howard Hinnantadff4892010-05-24 17:49:41 +000018 if (__t_ != 0)
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000019 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");
Howard Hinnantadff4892010-05-24 17:49:41 +000028 __t_ = 0;
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000029}
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{
Howard Hinnantadff4892010-05-24 17:49:41 +000048#if defined(CTL_HW) && defined(HW_NCPU)
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000049 int n;
50 int mib[2] = {CTL_HW, HW_NCPU};
51 std::size_t s = sizeof(n);
52 sysctl(mib, 2, &n, &s, 0, 0);
53 return n;
Howard Hinnantadff4892010-05-24 17:49:41 +000054#else // !defined(CTL_HW && HW_NCPU)
55 // TODO: grovel through /proc or check cpuid on x86 and similar
56 // instructions on other architectures.
57 return 0; // Means not computable [thread.thread.static]
58#endif
Howard Hinnantbc8d3f92010-05-11 19:42:16 +000059}
60
61namespace this_thread
62{
63
64void
65sleep_for(const chrono::nanoseconds& ns)
66{
67 using namespace chrono;
68 if (ns >= nanoseconds::zero())
69 {
70 timespec ts;
71 ts.tv_sec = static_cast<decltype(ts.tv_sec)>(duration_cast<seconds>(ns).count());
72 ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns - seconds(ts.tv_sec)).count());
73 nanosleep(&ts, 0);
74 }
75}
76
77} // this_thread
78
79_LIBCPP_END_NAMESPACE_STD