semaphore_wrapper.cc 2.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
/*!
 *  Copyright (c) 2021 by Contributors
 * \file semaphore_wrapper.cc
 * \brief A simple corss platform semaphore wrapper
 */
#include "semaphore_wrapper.h"

#include <dmlc/logging.h>

10
11
12
13
14
15
#ifndef _WIN32
#include <errno.h>
#include <time.h>
#include <unistd.h>
#endif

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace dgl {
namespace runtime {

#ifdef _WIN32

Semaphore::Semaphore() {
  sem_ = CreateSemaphore(nullptr, 0, INT_MAX, nullptr);
  if (!sem_) {
    LOG(FATAL) << "Cannot create semaphore";
  }
}

void Semaphore::Wait() {
  WaitForSingleObject(sem_, INFINITE);
}

32
33
34
35
36
37
bool Semaphore::TimedWait(int) {
  // Timed wait is not supported on WIN32.
  Wait();
  return true;
}

38
39
40
41
42
43
44
45
46
47
48
49
50
51
void Semaphore::Post() {
  ReleaseSemaphore(sem_, 1, nullptr);
}

#else

Semaphore::Semaphore() {
  sem_init(&sem_, 0, 0);
}

void Semaphore::Wait() {
  sem_wait(&sem_);
}

52
bool Semaphore::TimedWait(int timeout) {
53
54
55
56
57
  // sem_timedwait does not exist in Mac OS.
#ifdef __APPLE__
  DLOG(WARNING) << "Timeout is not supported in semaphore's wait on Mac OS.";
  Wait();
#else
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  // zero timeout means wait infinitely
  if (timeout == 0) {
    DLOG(WARNING) << "Will wait infinitely on semaphore until posted.";
    Wait();
    return true;
  }
  timespec ts;
  if (clock_gettime(CLOCK_REALTIME, &ts) != 0) {
    LOG(ERROR) << "Failed to get current time via clock_gettime. Errno: "
               << errno;
    return false;
  }
  ts.tv_sec += timeout / MILLISECONDS_PER_SECOND;
  ts.tv_nsec +=
      (timeout % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
  if (ts.tv_nsec >= NANOSECONDS_PER_SECOND) {
    ts.tv_nsec -= NANOSECONDS_PER_SECOND;
    ++ts.tv_sec;
  }
  int ret = 0;
  while ((ret = sem_timedwait(&sem_, &ts) != 0) && errno == EINTR) {
    continue;
  }
  if (ret != 0) {
    if (errno == ETIMEDOUT) {
      DLOG(WARNING) << "sem_timedwait timed out after " << timeout
                    << " milliseconds.";
    } else {
      LOG(ERROR) << "sem_timedwait returns unexpectedly. Errno: " << errno;
    }
    return false;
  }
90
91
#endif

92
93
94
  return true;
}

95
96
97
98
99
100
101
102
void Semaphore::Post() {
  sem_post(&sem_);
}

#endif

}  // namespace runtime
}  // namespace dgl