-
Notifications
You must be signed in to change notification settings - Fork 6
Multicore
Yuki Takei edited this page Oct 11, 2016
·
3 revisions
A single instance of Slimane runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Slimane processes to handle the load.
A Master and Worker Pattern Example.
The request(handle) that came to master is send to worker via ipc. The worker is determined with simple round robin algorithm.
// For Cluster app
if Cluster.isMaster {
for _ in 0..<OS.cpus().count {
let worker = try! Cluster.fork(silent: false)
}
try! Slimane().listen()
} else {
let app = Slimane()
app.get("/") { request, response, responder in
var response = response
response.text("Hello! process id is \(Process.pid)")
responder(.respond(response))
}
try! app.listen()
}
IPC between Master and Worker Processes
var worker = try! Cluster.fork(silent: false)
// Send message to the worker
worker.send(.Message("message from master"))
// Receive event from the worker
worker.onEvent { event in
if case .message(let str) = event {
print(str)
}
else if case .online = event {
print("Worker: \(worker.id) is online")
}
else if case .exit(let status) = event {
print("Worker: \(worker.id) is dead. status: \(status)")
let worker = try! Cluster.fork(silent: false)
observeWorker(worker)
}
}
// Receive event from the master
Process.onEvent { event in
if case .message(let str) = event {
print(str)
}
}
// Send message to the master
Process.send(.message("Hey!"))