semaphore_wrapper.cc 2.05 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
namespace dgl {
namespace runtime {

#ifdef _WIN32

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

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

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

36
void Semaphore::Post() { ReleaseSemaphore(sem_, 1, nullptr); }
37
38
39

#else

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

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

44
bool Semaphore::TimedWait(int timeout) {
45
46
47
48
49
  // 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
  // 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;
  }
82
83
#endif

84
85
86
  return true;
}

87
void Semaphore::Post() { sem_post(&sem_); }
88
89
90
91
92

#endif

}  // namespace runtime
}  // namespace dgl