-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathLocalCluster.h
More file actions
62 lines (47 loc) · 1.99 KB
/
LocalCluster.h
File metadata and controls
62 lines (47 loc) · 1.99 KB
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
/* This header is highly experimental and needs refactorings but will do for now */
#include <thread>
#include <algorithm>
#include <mutex>
unsigned int roundRobin = 0;
unsigned int hardwareConcurrency = std::thread::hardware_concurrency();
std::vector<std::thread *> threads(hardwareConcurrency);
std::vector<uWS::SSLApp *> apps;
std::mutex m;
namespace uWS {
struct LocalCluster {
//std::vector<std::thread *> threads = std::thread::hardware_concurrency();
//std::vector<uWS::SSLApp *> apps;
//std::mutex m;
static void loadBalancer() {
static std::atomic<unsigned int> roundRobin = 0; // atomic fetch_add
}
LocalCluster(SocketContextOptions options = {}, std::function<void(uWS::SSLApp &)> cb = nullptr) {
std::transform(threads.begin(), threads.end(), threads.begin(), [options, &cb](std::thread *) {
return new std::thread([options, &cb]() {
// lock this
m.lock();
apps.emplace_back(new uWS::SSLApp(options));
uWS::SSLApp *app = apps.back();
cb(*app);
app->preOpen([](LIBUS_SOCKET_DESCRIPTOR fd) -> LIBUS_SOCKET_DESCRIPTOR {
/* Distribute this socket in round robin fashion */
//std::cout << "About to load balance " << fd << " to " << roundRobin << std::endl;
auto receivingApp = apps[roundRobin];
apps[roundRobin]->getLoop()->defer([fd, receivingApp]() {
receivingApp->adoptSocket(fd);
});
roundRobin = (roundRobin + 1) % hardwareConcurrency;
return (LIBUS_SOCKET_DESCRIPTOR) -1;
});
m.unlock();
app->run();
std::cout << "Fallthrough!" << std::endl;
delete app;
});
});
std::for_each(threads.begin(), threads.end(), [](std::thread *t) {
t->join();
});
}
};
}