summaryrefslogtreecommitdiffstats
path: root/src/thread.cpp
blob: 4a7904dc5423ae5409b0af7ed8027cfd6da15d01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//===------------------------- thread.cpp----------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "thread"
#include "exception"
#include <sys/sysctl.h>

_LIBCPP_BEGIN_NAMESPACE_STD

thread::~thread()
{
    if (__t_ != nullptr)
        terminate();
}

void
thread::join()
{
    int ec = pthread_join(__t_, 0);
    if (ec)
        throw system_error(error_code(ec, system_category()), "thread::join failed");
    __t_ = nullptr;
}

void
thread::detach()
{
    int ec = EINVAL;
    if (__t_ != 0)
    {
        ec = pthread_detach(__t_);
        if (ec == 0)
            __t_ = 0;
    }
    if (ec)
        throw system_error(error_code(ec, system_category()), "thread::detach failed");
}

unsigned
thread::hardware_concurrency()
{
    int n;
    int mib[2] = {CTL_HW, HW_NCPU};
    std::size_t s = sizeof(n);
    sysctl(mib, 2, &n, &s, 0, 0);
    return n;
}

namespace this_thread
{

void
sleep_for(const chrono::nanoseconds& ns)
{
    using namespace chrono;
    if (ns >= nanoseconds::zero())
    {
        timespec ts;
        ts.tv_sec = static_cast<decltype(ts.tv_sec)>(duration_cast<seconds>(ns).count());
        ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((ns - seconds(ts.tv_sec)).count());
        nanosleep(&ts, 0);
    }
}

}  // this_thread

_LIBCPP_END_NAMESPACE_STD