@@ -2423,3 +2423,65 @@ TODO: Talk about how to dynamically change the number of shares, and why.
2423
2423
2424
2424
## Multi-tenancy
2425
2425
TODO
2426
+
2427
+ # General application structuring tips
2428
+
2429
+ ## Initialization and cleanup
2430
+
2431
+ In C++, RAII is typically used to coordinate initialization and cleanup. In asyncronous programming, RAII
2432
+ is not available, but for the control plane it is useful to bring up a seastar::thread to make use of it.
2433
+
2434
+ In conjunction with seastar::app_template, initialization and cleanup look like so:
2435
+
2436
+ ``` cpp
2437
+ #include < seastar/core/app-template.hh>
2438
+ #include < seastar/core/reactor.hh>
2439
+ #include < iostream>
2440
+
2441
+ int main (int argc, char** argv) {
2442
+ seastar::app_template app;
2443
+ return app.run(argc, argv, [ ] {
2444
+ return seastar::async() {
2445
+ std::cout << "Hello world\n";
2446
+ my_class my_object;
2447
+ // ... more code
2448
+
2449
+ // my_object will be destroyed here
2450
+ return 0;
2451
+ });
2452
+ }
2453
+ ```
2454
+
2455
+ If one needs to invoke an asynchronous function during shutdown, one can make
2456
+ use of the seastar::defer() function to schedule an arbitrary cleanup function:
2457
+
2458
+ ```cpp
2459
+ #include <seastar/core/app-template.hh>
2460
+ #include <seastar/core/reactor.hh>
2461
+ #include <iostream>
2462
+
2463
+ int main(int argc, char** argv) {
2464
+ seastar::app_template app;
2465
+ return app.run(argc, argv, [] {
2466
+ return seastar::async() {
2467
+ std::cout << "Hello world\n";
2468
+ my_class my_object;
2469
+ // ... more code
2470
+
2471
+ auto cleanup = defer([] () noexcept {
2472
+ // .get() joins the asynchronous function back
2473
+ // into the thread.
2474
+ call_async_cleanup_function().get();
2475
+ });
2476
+
2477
+ // `cleanup` will invoke its function here, if we reached
2478
+ // its construction point
2479
+
2480
+ // my_object will be destroyed here
2481
+ return 0;
2482
+ });
2483
+ }
2484
+ ```
2485
+
2486
+ See also seastar::deferred_close and seastar::deferred_stop for more ways to
2487
+ control cleanup.
0 commit comments