blob: f2db6d51b23b1d7ed09f01227037125ef3daca4a [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"
Howard Hinnantd031c582010-05-25 17:25:25 +000012#include <sys/types.h>
Howard Hinnantc51e1022010-05-11 19:42:16 +000013#include <sys/sysctl.h>
14
15_LIBCPP_BEGIN_NAMESPACE_STD
16
17thread::~thread()
18{
Howard Hinnant155c2af2010-05-24 17:49:41 +000019 if (__t_ != 0)
Howard Hinnantc51e1022010-05-11 19:42:16 +000020 terminate();
21}
22
23void
24thread::join()
25{
26 int ec = pthread_join(__t_, 0);
27 if (ec)
28 throw system_error(error_code(ec, system_category()), "thread::join failed");
Howard Hinnant155c2af2010-05-24 17:49:41 +000029 __t_ = 0;
Howard Hinnantc51e1022010-05-11 19:42:16 +000030}
31
32void
33thread::detach()
34{
35 int ec = EINVAL;
36 if (__t_ != 0)
37 {
38 ec = pthread_detach(__t_);
39 if (ec == 0)
40 __t_ = 0;
41 }
42 if (ec)
43 throw system_error(error_code(ec, system_category()), "thread::detach failed");
44}
45
46unsigned
47thread::hardware_concurrency()
48{
Howard Hinnant155c2af2010-05-24 17:49:41 +000049#if defined(CTL_HW) && defined(HW_NCPU)
Howard Hinnantc51e1022010-05-11 19:42:16 +000050 int n;
51 int mib[2] = {CTL_HW, HW_NCPU};
52 std::size_t s = sizeof(n);
53 sysctl(mib, 2, &n, &s, 0, 0);
54 return n;
Howard Hinnant155c2af2010-05-24 17:49:41 +000055#else // !defined(CTL_HW && HW_NCPU)
56 // TODO: grovel through /proc or check cpuid on x86 and similar
57 // instructions on other architectures.
58 return 0; // Means not computable [thread.thread.static]
59#endif
Howard Hinnantc51e1022010-05-11 19:42:16 +000060}
61
62namespace this_thread
63{
64
65void
66sleep_for(const chrono::nanoseconds& ns)
67{
68 using namespace chrono;
69 if (ns >= nanoseconds::zero())
70 {
71 timespec ts;
72 ts.tv_sec = static_cast<decltype(ts.tv_sec)>(duration_cast<seconds>(ns).count());
73 ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns - seconds(ts.tv_sec)).count());
74 nanosleep(&ts, 0);
75 }
76}
77
78} // this_thread
79
80_LIBCPP_END_NAMESPACE_STD