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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#pragma once
namespace NActors {
class TSelectThread : public TPollerThreadBase<TSelectThread> {
TMutex Mutex;
std::unordered_map<SOCKET, TIntrusivePtr<TSocketRecord>> Descriptors;
enum {
READ = 1,
WRITE = 2,
};
public:
TSelectThread(TActorSystem *actorSystem)
: TPollerThreadBase(actorSystem)
{
Descriptors.emplace(ReadEnd, nullptr);
ISimpleThread::Start();
}
~TSelectThread() {
Stop();
}
bool ProcessEventsInLoop() {
fd_set readfds, writefds, exceptfds;
FD_ZERO(&readfds);
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
int nfds = 0;
with_lock (Mutex) {
for (const auto& [key, record] : Descriptors) {
const int fd = key;
auto add = [&](auto& set) {
FD_SET(fd, &set);
nfds = Max<int>(nfds, fd + 1);
};
if (!record || (record->Flags & READ)) {
add(readfds);
}
if (!record || (record->Flags & WRITE)) {
add(writefds);
}
add(exceptfds);
}
}
int res = select(nfds, &readfds, &writefds, &exceptfds, nullptr);
if (res == -1) {
const int err = LastSocketError();
if (err == EINTR) {
return false; // try a bit later
} else {
Y_FAIL("select() failed with %s", strerror(err));
}
}
bool flag = false;
with_lock (Mutex) {
for (const auto& [fd, record] : Descriptors) {
if (record) {
const bool error = FD_ISSET(fd, &exceptfds);
const bool read = error || FD_ISSET(fd, &readfds);
const bool write = error || FD_ISSET(fd, &writefds);
if (read) {
record->Flags &= ~READ;
}
if (write) {
record->Flags &= ~WRITE;
}
Notify(record.Get(), read, write);
} else {
flag = true;
}
}
}
return flag;
}
void UnregisterSocketInLoop(const TIntrusivePtr<TSharedDescriptor>& socket) {
with_lock (Mutex) {
Descriptors.erase(socket->GetDescriptor());
}
}
void RegisterSocket(const TIntrusivePtr<TSocketRecord>& record) {
with_lock (Mutex) {
Descriptors.emplace(record->Socket->GetDescriptor(), record);
}
ExecuteSyncOperation(TPollerWakeup());
}
void Request(const TIntrusivePtr<TSocketRecord>& record, bool read, bool write) {
with_lock (Mutex) {
const auto it = Descriptors.find(record->Socket->GetDescriptor());
Y_VERIFY(it != Descriptors.end());
it->second->Flags |= (read ? READ : 0) | (write ? WRITE : 0);
}
ExecuteSyncOperation(TPollerWakeup());
}
};
using TPollerThread = TSelectThread;
} // NActors
|