forked from Chia-Network/chiapos
-
Notifications
You must be signed in to change notification settings - Fork 1
/
threading.hpp
68 lines (63 loc) · 1.81 KB
/
threading.hpp
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
//
// Created by Mariano Sorgente on 2020/09/27.
//
#ifndef CHIAPOS_THREADING_HPP
#define CHIAPOS_THREADING_HPP
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#define STRICT
#include <windows.h>
#elif __APPLE__
#include <unistd.h>
#include <dispatch/dispatch.h>
#else
#include <unistd.h>
#include <semaphore.h>
#endif
// TODO: in C++20, this can be replaced with std::binary_semaphore
namespace Sem {
#ifdef _WIN32
using type = HANDLE;
inline void Wait(HANDLE* semaphore) { WaitForSingleObject(*semaphore, INFINITE); }
inline void Post(HANDLE* semaphore) { ReleaseSemaphore(*semaphore, 1, NULL); }
inline HANDLE Create() {
return CreateSemaphore(
nullptr, // default security attributes
0, // initial count
2, // maximum count
nullptr); // unnamed semaphore
}
inline void Destroy(HANDLE sem) {
CloseHandle(sem);
}
#elif __APPLE__
using type = dispatch_semaphore_t;
inline void Wait(dispatch_semaphore_t *semaphore) {
dispatch_semaphore_wait(*semaphore, DISPATCH_TIME_FOREVER);
}
inline void Post(dispatch_semaphore_t *semaphore) {
dispatch_semaphore_signal(*semaphore);
}
inline dispatch_semaphore_t Create() {
return dispatch_semaphore_create(0);
}
inline void Destroy(dispatch_semaphore_t sem) {
dispatch_release(sem);
}
#else
using type = sem_t;
inline void Wait(sem_t *semaphore) { sem_wait(semaphore); }
inline void Post(sem_t *semaphore) { sem_post(semaphore); }
inline sem_t Create() {
sem_t ret;
sem_init(&ret, 0, 0);
return ret;
}
inline void Destroy(sem_t& sem) {
sem_close(&sem);
}
#endif
};
// std::cout << ptd->index << " waited 0" << std::endl;
#endif // CHIAPOS_THREADING_HPP