kirit.com

Created 26th April, 2005 13:12 (UTC), last edited 22nd December, 2016 03:24 (UTC)

Writing about C++, Programming, Fost 5, the web, Thailand and anything else that catches my attention—with some photos thrown in

Fost 5 release 5.18.03.45059 now out

Posted 26th March, 2018 04:11 (UTC), last edited 26th March, 2018 08:53 (UTC)

The Mac builds are finally back! This means we now have Linux, Mac and Android. Regaining iOS support is still something for the future.

The Mac build does drop the Python 2 bindings and the Wright application. Wright isn't going to be a loss, and the Python 2 bindings need to be deprecated in favour of a newer set of Python 3 ones.

One upshot of this is that the oldest compiler we need to support is now likely to be the Mac one rather than the Android one, but it's hard to tell because Apple have a completely different versioning scheme than the llvm project uses.

There have been many changes to the string handling. This is still leading up to the large refactoring. The u8view has become much more useful and there is a shared version of this in the works. Eventually this will lead to the replacement and deprecation of the fostlib::string for a variant based constant string, and the use of std::string everywhere else.

There has also been more cleaning up and removing of Boost libraries. You may find you need to now include Boost threading headers or Boost function headers.

Building on Linux & Mac

git clone --branch=5.18.03.45059 --recursive git@github.com:KayEss/fost-hello.git
cd fost-hello
Boost/build
hello/compile
dist/bin/hello-world-d

On the Mac you will need to set DYLD_LIBRARY_PATH before running hello-world-d

export DYLD_LIBRARY_PATH=dist/lib
dist/bin/hello-world-d

Download locations

Applications

  • beanbag — Stand alone transactional JSON database server — git@github.com:KayEss/beanbag.git
  • beanbag-seed — Seed project for giving you a starting point to develop web applications using Beanbag — git@github.com:KayEss/beanbag-seed.git
  • fost-hello — Sample seed project — git@github.com:KayEss/fost-hello.git
  • mengmon — Stand alone web server — git@github.com:KayEss/mengmom.git
  • wright — Experimental build system — git@github.com:KayEss/wright.git

Libraries

  • f5-cord — First version of a new string library with compile time string and Unicode support — git@github.com:KayEss/f5-cord.git
  • f5-threading — Preview of the first Fost 5 library which includes help for threading — git@github.com:KayEss/f5-threading.git
  • fost-aws — Amazon AWS and OpenStack — git@github.com:KayEss/fost-aws.git
  • fost-android — Eclipse project for Android that allows Fost 4 and Beanbags to be used on mobile devices — git@github.com:KayEss/fost-android.git
  • fost-android-ndk — The native code for Android. Includes required parts of Boost configured to use the standard Android build system.
  • fost-beanbag — Transactional JSON database — git@github.com:KayEss/fost-beanbag.git
  • fost-base — Build system and core libraries — git@github.com:KayEss/fost-base.git
  • fost-internet — Internet protocols, servers & clients — git@github.com:KayEss/fost-internet.git
  • fost-meta — All libraries in one wrapper — git@github.com:KayEss/fost-meta.git
  • fost-orm — Object/Relational mapping — git@github.com:KayEss/fost-orm.git
  • fost-postgres — PostgreSQL — git@github.com:KayEss/fost-postgres.git
  • fost-py — Python (2.x) bindings — git@github.com:KayEss/fost-py.git
  • fost-web — Web server libraries — git@github.com:KayEss/fost-web.git
  • fost-wright — Experiment in a build system — git@github.com:KayEss/fost-wright.git

Detailed change log

cord

  • Add empty to the u8view and buffers.
  • Add ability to output u8view and move overloaded operator <<s to std namespace.
  • Allow appending of a u8view to a std::string.
  • u8views can be concatenated to form std::strings.
  • u8view supports operator <.
  • lstring now also has a string literal, _l.
  • Add empty() member to lstirng.
  • The const shared string buffers need to be immutable.
  • u8view can be explicitly converted to a std::string.
  • u8view is now comparable with const char *.

threading

  • Don't include any Fost headers.
  • Bypass the coroutine unwind exceptions for the reactor and sync.
  • Move the reactor_pool to reactor.hpp
  • The reactor_pool can be closed and its threads joined at any time.

fostgres

  • Fix the fg parser to allow whitespace and comments in more places.

fost-aws

  • Removed use of boost::function.

fost-base

  • Fix bug to handle requirements for autotest libraries properly.
  • Removed Boost lambda and bind
  • Remove previously deprecated fostlib::counter.
  • Allow the C++ version to be specified as std-version in the requirments.jam file.
  • crypto_compare works with Unicode strings.
  • More tagged strings can now be coerced to json and to f5::u8view.
  • Improve the converting nullable constructor so it uses explicit type conversions.
  • Make more string utilties compatible with f5::u8view, at the cost of wide character literals.
  • Make nullable<f5::u8view> coercions from JSON not throw errors if the value isn't a string.
  • Improve the jcursor APIs to better support u8view and move semantics.
  • Add f5::lstring as an option for storage inside fostlib::json.
  • Control characters need to be escaped when producing JSON strings.
  • Can now mint a JWT with an initial payload.
  • Remove uses of boost::function and make worker const sane.
  • Add missing namespaces to the log definition macros.
  • Small readability improvement to the default stdout logger.
  • Crypto hashes now take a f5::u8view which should remove some memory allocations.
  • Deprecate fostlib::utf::u8_view in favour of f5::u8view
  • Move utf::u8_view to f5-cord.
  • Remove array_view and replace with f5::array_view from f5-cord.
  • Deprecate use of the fostlib::string JSON coercion in favour of utf::u8_view.

fost-internet

  • Make the query_string API a bit less pathalogical by caching the stringified version.
  • JSON arrays used as header sub-values are now set as the JSON string.
  • Removed all uses of boost::function

fost-orm

  • Remove all instances of boost::function

fost-postgres

  • Put session variable names in double quotes.
  • Changed the upsert function to also take an array of strings for a RETURNING clause.

fost-py

  • Fix a problem with Boost 1.65

wright

  • Work is distributed between workers more evenly.

Categories:

Fost 5 release 5.17.12.45058 now out

Posted 28th December, 2017 04:42 (UTC), last edited 28th December, 2017 08:32 (UTC)

This release includes a step towards revised string handling. The eventual goal is to be able to remove the fostlib::string from most places in favour of a smarter structure based on a std::variant that can better handle different string sources. This work is ongoing and you can see progress in the develop branches.

We're also taking a look at macos and Windows again, but both platforms are quite difficult so no real progress yet.

Building on Linux

You will need a C++14 compiler. Recent versions of either gcc or clang are suitable.

git clone --branch=5.17.12.45058 --recursive git@github.com:KayEss/fost-hello.git
cd fost-hello
Boost/build
hello/compile
dist/bin/hello-world-d

Download locations

Applications

  • beanbag — Stand alone transactional JSON database server — git@github.com:KayEss/beanbag.git
  • beanbag-seed — Seed project for giving you a starting point to develop web applications using Beanbag — git@github.com:KayEss/beanbag-seed.git
  • fost-hello — Sample seed project — git@github.com:KayEss/fost-hello.git
  • mengmon — Stand alone web server — git@github.com:KayEss/mengmom.git
  • wright — Experimental build system — git@github.com:KayEss/wright.git

Libraries

  • f5-cord — First version of a new string library with compile time string and Unicode support — git@github.com:KayEss/f5-cord.git
  • f5-threading — Preview of the first Fost 5 library which includes help for threading — git@github.com:KayEss/f5-threading.git
  • fost-aws — Amazon AWS and OpenStack — git@github.com:KayEss/fost-aws.git
  • fost-android — Eclipse project for Android that allows Fost 4 and Beanbags to be used on mobile devices — git@github.com:KayEss/fost-android.git
  • fost-android-ndk — The native code for Android. Includes required parts of Boost configured to use the standard Android build system.
  • fost-beanbag — Transactional JSON database — git@github.com:KayEss/fost-beanbag.git
  • fost-base — Build system and core libraries — git@github.com:KayEss/fost-base.git
  • fost-internet — Internet protocols, servers & clients — git@github.com:KayEss/fost-internet.git
  • fost-meta — All libraries in one wrapper — git@github.com:KayEss/fost-meta.git
  • fost-orm — Object/Relational mapping — git@github.com:KayEss/fost-orm.git
  • fost-postgres — PostgreSQL — git@github.com:KayEss/fost-postgres.git
  • fost-py — Python (2.x) bindings — git@github.com:KayEss/fost-py.git
  • fost-web — Web server libraries — git@github.com:KayEss/fost-web.git
  • fost-wright — Experiment in a build system — git@github.com:KayEss/fost-wright.git

Detailed change log

cord

  • Add string equality comparison and substr operations to u8view.
  • Fill in more of the lstring comparison members.
  • Add shared buffers who can own strings (and other things).
  • Rename array_view to buffer as it is not always immutable.
  • Add u8view and UTF8 decode function.
  • Added an array_view with some constexpr support.

fostgres

  • Add scripting call setting for manipulating settings.
  • Add parser support for all JSON atom values.
  • Add RETURNING support to PUT request for objects.
  • Move some tests so Postgres is not needed for a normal build.

Categories:

Pacific++ trip report

Posted 31st October, 2017 02:25 (UTC), last edited 2nd November, 2017 01:31 (UTC)

Pacific++ is the first programming language conference I've been to, and I have to say that actually being there is a big step up from just watching videos on youtube. The conference was small and intimate, which was great. I think I probably managed to talk to nearly half of the about 70 attendees. We got mugs

Day 1

Chandler Carruth opened with a live demo (video) of how to build clang and it's tooling and then went on to demo some of the other features.

I've been building a toolchain for our internal use so that we're able to make use of the new coroutines features that shipped with clang 5. I'd kind of expected this to be a short term thing so hadn't put too much effort into it, so it was interesting to learn that Google actually do this weekly just using HEAD of master for all of their builds. Maybe tidying this up for long term use will be good.

One thing Chandler didn't talk about is how they distrubute the toolchain to developers, a problem I think we've solved quite well using docker. I think it's something that I should probably blog about.

Making use of the llvm linker (-fuse-ld=lld, it's much faster) and the use of the link time optimiser (-flto=thin) also looked worthwhile.

He also showed us the CFI sanitizer (-fsanitize=cfi) which is designed to help harden your code in production (important for our networking code).

Chandler only needed four and half minutes to compile all of clang, but he did later admit that he was using a 128 core monster he has at home built especially to make clang builds fast.

Next up Toby Allsopp talked about coroutines (video). He gave a general high level overview of how they work and some of the things you can do with them, and most importantly, showed the benefits they bring in terms of code clarity. He has some great diagrams of the control flow through the coroutine and its calling function which would certainly help my tutorial articles. I'll be linking his from the introduction article once it's up on youtube.

Matt Bentley took us through his higher performance list implementation (video) which uses an allocation scheme that tries to keep list cells contiguous in memory as far as possible. It turns out that there are many places that the common wisdom of always just using a vector isn't the best for performance and he showed us places where list implementations (especially his) do win out.

Dean Michael Berris explained how XRay works, which is a tool for gathering performance data about the execution of your code, and is fast enough that it can be used in production systems with the data gathering turned on and off whilst the system is running.

This looks like a very interesting capability that is now included in newer versions of clang (and is yet another reason why building your toolchain is worthwhile).

Dean took us through the low level implementation details of how the instrumentation is turned on and off at runtime and why the overhead is so low. He also showed some of the (offline) analysis tools that come with XRay.

Right now it doesn't support shared objects (dynamic linking with .so files), but Dean promised me that was work in progress. Still more reason to stay as near to HEAD with llvm as possible—and, if whoever is working on it needs somebody to test it out then please let me know :)

The final talk was Christian Blume's about his transwarp library, which is able to build up a graph (acyclic tree only) of tasks with the dependencies and then execute it multiple times (the other approach is to build the tree for each group of tasks and then rip it down when they've executed).

It takes a very different approach to how this would look with coroutines or the ranges TS, which may be easier to work with where the dependancy graph is only known at runtime.

At the end of the time there was much lively discussion in the bar followed by the speaker's dinner which I'd decided to pay the extra for given that I was there on my own and figured it would be a good opportunity to talk to more people (spoiler, it was well worth it).

At the dinner Chandler came out with a very interesting rant on the difficulties compilers have with user defined literals, especially for compile string handling of the type I've been playing around with in f5-cord's tstringclass — Oops, and somethingh I'll have to think more about. Not only are there parsing problems with them, but more importantly, compile time substring processing is especially costly in terms of compile times (thankfully not something I care about).

Day 2

The second day started off with Jason Turner (video) telling us about the importance of noexcept. I'd always not worried too much about it because I thought that the overhead of having to manage the terminate condition mandated in the standard would negate any possible code generation improvements. Jason managed to show that was categorically false, and even more importantly demonstrated many code improvements directly driven by trying to make things noexcept that should be.

Carl Cook showed a number of techniques used by high frequency trading developers to reduce latency when trading. I've been watching a lot of high throughput videos by games developers and then applying those techniques to Postgres database designs, so it was interesting to see some low latency examples too. For some of the things we want to do latency can be important so now I need to think about how to apply these techniques to databases.

Wanting to implement state machines was a big reason for me to pick up coroutines, after watching Dominic Robinson's ACCU talk, so it was great to see what Nick Sarten had done through using std::variant. He benchmarked a few different approaches, including one based on inheritance. This implementation, like a coroutine based one, performs a memory allocation on state change and the benchmarks showed just how expensive that would be. Something we're going to need to think a lot more about.

Sarah Smith is a much braver person than me clearly. I've done some live coding talks, but she built an entire application using Qt and then ran it on her desktop and phone (iOS, of course the Android had problems connecting to the dev environment, as they always do).

She also talked about her history and how she ended up a mobile developer and entrepreneur. I always love to hear stories about how people ended up where they are.

The final talk was Tom Isaacson showing how, what look like the same warnings, actually differ a lot between compilers and how that affects cross platform development. I don't switch warnings to errors because of the range of different compilers we use, but I can certainly see the appeal and it would be good to tighten this up and turn on more warnings. He showed some interesting ones that are not turned on by default.

Go to a conference

This was my first C++ conference (actually, my first real tech conference), and it was well worth the trip. I've watched a lot of videos from other conferences, and although great, it's not anything like actually being there and getting to talk to people.

I think my next mission should be to make it to the ACCU conference in the UK.


I'll link the videos as they come online. If any other links are wrong, or could be better elsewhere please let me know. I've probably misunderstood what people were trying to say in their talks, mistakes are my own.


Categories:

Fost 5 release 5.17.09.45051 now out

Posted 23rd September, 2017 03:51 (UTC), last edited 23rd September, 2017 04:12 (UTC)

The layout changes to fostlib::json have now landed. Previously the atomic parts of JSON (bool, int, double, string etc.) where stored in a separate variant to the one that handled the atomic, array and object parts. By bringing this all into one variant the type is smaller and dealing with atomic types is faster.

As part of this change we also changed the object and array to being stored by a shared_ptr rather than directly. This was always the intended design, and means that now taking a copy of a json is significantly cheaper. We have some more changes coming now that we have this base that should make the type smaller still and further improve performance.

We're also still moving towards improving string handling with a few new immutable string types in the pipeline and a move towards using immutable string views in many more places.

It's also about time that we get serious with Python 3 support. All of our projects are now using this and we need to be able to support bindings for it correctly. There's still some debate about whether that should be a branch in fost-py or a separate library. In any case the entirety of the Python 2 version will be replaced with something completely new.

Building on Linux

You will need a C++14 compiler. Recent versions of either gcc or clang are suitable.

git clone --branch=5.17.09.45051 --recursive git@github.com:KayEss/fost-hello.git
cd fost-hello
Boost/build
hello/compile
dist/bin/hello-world-d

Download locations

Applications

  • beanbag — Stand alone transactional JSON database server — git@github.com:KayEss/beanbag.git
  • beanbag-seed — Seed project for giving you a starting point to develop web applications using Beanbag — git@github.com:KayEss/beanbag-seed.git
  • fost-hello — Sample seed project — git@github.com:KayEss/fost-hello.git
  • mengmon — Stand alone web server — git@github.com:KayEss/mengmom.git
  • wright — Experimental build system — git@github.com:KayEss/wright.git

Libraries

  • f5-cord — First version of a new string library with compile time string and Unicode support — git@github.com:KayEss/f5-cord.git
  • f5-threading — Preview of the first Fost 5 library which includes help for threading — git@github.com:KayEss/f5-threading.git
  • fost-aws — Amazon AWS and OpenStack — git@github.com:KayEss/fost-aws.git
  • fost-android — Eclipse project for Android that allows Fost 4 and Beanbags to be used on mobile devices — git@github.com:KayEss/fost-android.git
  • fost-android-ndk — The native code for Android. Includes required parts of Boost configured to use the standard Android build system.
  • fost-beanbag — Transactional JSON database — git@github.com:KayEss/fost-beanbag.git
  • fost-base — Build system and core libraries — git@github.com:KayEss/fost-base.git
  • fost-internet — Internet protocols, servers & clients — git@github.com:KayEss/fost-internet.git
  • fost-meta — All libraries in one wrapper — git@github.com:KayEss/fost-meta.git
  • fost-orm — Object/Relational mapping — git@github.com:KayEss/fost-orm.git
  • fost-postgres — PostgreSQL — git@github.com:KayEss/fost-postgres.git
  • fost-py — Python (2.x) bindings — git@github.com:KayEss/fost-py.git
  • fost-web — Web server libraries — git@github.com:KayEss/fost-web.git
  • fost-wright — Experiment in a build system — git@github.com:KayEss/fost-wright.git

Detailed change log

cord

  • Add a _t literal for creating tstring instances. This allows us to deprecate the vstring template.
  • Added iostream output for lstring.

fostgres

  • Add -h and -U options to fostgres-test to control how to access the database.

fost-base

  • Fix generation of log messages from JSON where the modules are an array.
  • Count the number of times an exception has been absorbed.
  • Remove variant for storing atoms in json
  • Don't print empty objects in the log stream.
  • Load the global logging configuration much later so it can be changed using the -i or -j command line switches.
  • Better integrate utf::u8_view and string.
  • Make array_view sliceable.
  • There is now an explicit constructor from std::string for the u8_view.
  • Make dates fully comparable.
  • Improve error report when coercing JSON to strings fails.
  • The unexpected_eof error can now take a boost::system::error_code for use with socket errors.

fost-internet

  • Ampersands, single quote and dollar symbol added to allowed URL path characters.
  • The conversion of HTTP request file paths to strings now works for a wider range of inputs. The conversion to boost::filesystem::wpath is problematic with Boost versions prior to 1.64 due to the way they use codecvt.

fost-orm

  • Improve error report when a beanbag update precondition wasn't met.

fost-postgres

  • Make it possible to iterate over the columns in the row.
  • Change libpqxx paths for latest code.
  • Implement assignment and pre-increment for recordset::const_iterator

fost-py

  • The spider always outputs a test.txt file with all results in it.

fost-web

  • The template middleware now uses the headers from the wrapped view instead of throwing them away.
  • Logging middleware also records the processing duration.

Categories:

Awaiting

Created 27th August, 2017 06:37 (UTC), last edited 27th August, 2017 06:55 (UTC)

We've covered co_return and co_yield now. The final new keyword introduced by the coroutines TS is co_await. Where the first two keywords allow a coroutine to suspend whilst its consumer gets ready to use results, co_await is used to allow the coroutine to suspend whilst it waits for things it needs. I tend to think of co_return and co_yield as servicing the outside of the coroutine and co_await as dealing with the inside.

We're going to start with the refactored lazy class that we had a couple of tutorials ago and make it so that our lazy class supports co_await.

lazy<int> answer() {
    std::cout << "Thinking deep thoghts..." << std::endl;
    co_return 42;
}

sync<int> await_answer() {
    std::cout << "Started await_answer" << std::endl;
    auto a = answer();
    std::cout << "Got a coroutine, let's get a value" << std::endl;
    auto v = co_await a;
    std::cout << "And the coroutine value is: " << v << std::endl;
    v = co_await a;
    std::cout << "And the coroutine value is still: " << v << std::endl;
    co_return 0;
}

int main() {
    return await_answer().get();
}

The first thing to notice here is that we now have two coroutines, both answer and await_answer. We can't perform the await inside main because main (along with constructors and destructors) isn't allowed to be a coroutine.

The reason for this is that a coroutine's return value needs to be properly dealt with from its calling context, so that the coroutine does its work properly. If we tried to turn main into a coroutine there'd be nothing to handle this for us. There're similar problems for both constructors and destructors, neither of which return values.

Because there are two coroutines in play we'll only keep the prints for the lifetime tracking of the lazy instance and not the sync one. We're using sync only as a mechanism to allow us to enter a context within which we can use coroutines and it doesn't play any part in the example other than that.

The co_await API

Just like our co_return and co_yield examples, the co_await requires a particular API on anything we want to await. There are three parts:

  1. await_ready returns a boolean to describe whether or not the suspend is needed, true for don't suspend and false for suspend.
  2. await_suspend which is called when the suspend is needed because the value isn't ready yet.
  3. await_resume which returns the value that is being awaited on. This becomes the result of the co_await expression.

Let's look at what these would look like for our lazy class.

bool await_ready() {
    const auto ready = coro.done();
    std::cout << "Await " << (ready ? "is ready" : "isn't ready") << std::endl;
    return coro.done();
}

We can easily tell if the value is available by looking to see if the lazy is done or not. If it is done then we can move directly on to returning the value to the co_await. If it isn't done we're going to need to resume the lazy body so it can co_return something into the promise type for us to pass on.

void await_suspend(std::experimental::coroutine_handle<> awaiting) {
    std::cout << "About to resume the lazy" << std::endl;
    coro.resume();
    std::cout << "About to resume the awaiter" << std::endl;
    awaiting.resume();
}

Here we can directly see the two coroutines in our example. The function is a member of the lazy returned by answer so the class member coro is the handle to the answer coroutine. We always resume this because we can only end up here if the coroutine isn't done already (checked in the await_ready member).

The passed in awaiting handle is for the sync instance associated with the await_answer coroutine, which is where the co_await appears. Once the lazy is done we resume this coroutine.

The last part (returning the value) is trivial:

auto await_resume() {
    const auto r = coro.promise().value;
    std::cout << "Await value is returned: " << r << std::endl;
    return r;
}

When we run this we can see things working as expected (remember that we only print lifetime information for the lazy instance and not the sync one):

Started await_answer
Promise created
Send back a lazy
Created a lazy object
Started the coroutine, wait for the go!
Move constructed a lazy object
Lazy gone
Got a coroutine, let's get a value
Await isn't ready
About to resume the lazy
Thinking deep thoghts…
Got an answer of 42
Finished the coro
About to resume the awaiter
Await value is returned: 42
And the coroutine value is: 42
Await is ready
Await value is returned: 42
And the coroutine value is still: 42
Promise died
Lazy gone

The first time await_ready is called the lazy hasn't yet run so we can see answer being entered when it is resumed and then the execution path as the value makes it way back out. The second time, however, the lazy is already done so we don't go down the resume path as we skip directly on to returning a second copy of the value.

Comparison with get

Let's look again at our get implementation:

T get() {
    std::cout << "We got asked for the return value..." << std::endl;
    if ( not coro.done() ) coro.resume();
    return coro.promise().value;
}

You'll notice that all the three parts of our new API appear in this:

  1. The if statement's conditional expression appears as await_ready
  2. The resume appears in the await_suspend.
  3. The return is handled by the await_resume.

There is one rather important difference though. The await_suspend also gets given the handle to the second coroutine, and this allows it to do a number of interesting things with it, all of which we'll have to wait for future tutorials for. We'll see our first example in the next article where we'll use co_await for something a bit more cool and surprising.

Addendum 1: operator co_await

The thing that is a bit nasty about this code is that the await API is implemented directly on the lazy instance and this allows it be used (and abused) by anybody who has a lazy instance. Luckily there is something we can do about that. We can add await support to any type by adding support for operator co_await. Like many of these operators it can be defined as a method, or stand alone. The signature for the the member version would be:

awaitable_type operator co_await();

Where awaitable_type now implements the above API. If we want it to be stand alone then it would be:

template<typename T>
awaitable_type operator co_await(lazy<T> &);

This is analagous to operators like == and <<.

Using this, and the new trick of local types we can use the following:

auto operator co_await() {
    struct awaitable_type {
        handle_type coro;
        bool await_ready() {
            const auto ready = coro.done();
            std::cout << "Await " << (ready ? "is ready" : "isn't ready") << std::endl;
            return coro.done();
        }
        void await_suspend(std::experimental::coroutine_handle<> awaiting) {
            std::cout << "Got to resume the lazy" << std::endl;
            coro.resume();
            std::cout << "Got to resume the awaiter" << std::endl;
            awaiting.resume();
        }
        auto await_resume() {
            const auto r = coro.promise().value;
            std::cout << "Await value is returned: " << r << std::endl;
            return r;
        }
    };
    return awaitable_type{coro};
}

Addendum 2: Tail call optimisation

In the current TS we have to resume both coroutines in the await_suspend. The lazy coroutine's body is executed first and when it suspends after the co_return our await_suspend resumes execution and then continues execution of the awaiting coroutine, in this case

void await_suspend(std::experimental::coroutine_handle<> awaiting) {
    std::cout << "About to resume the lazy" << std::endl;
    coro.resume();
    std::cout << "About to resume the awaiter" << std::endl;
    awaiting.resume();
}

It's not quite as dire as it seems though, because the call is in the tail position. This allows the compiler to perform tail call optimisation to remove the stack frame, something that the optimsers in modern compilers are pretty good at. This means optimised production builds should be fine, but it may prove a problem for debug builds.

To deal with this better a future version of the TS is likely to allow await_suspend to return a coroutine handle to be used as a continuation (that is, to be called immediately after await_suspend returns). This looks like:

auto await_suspend(std::experimental::coroutine_handle<> awaiting) {
    std::cout << "About to resume the lazy" << std::endl;
    coro.resume();
    std::cout << "Returning awaiting coroutine as a continuation" << std::endl;
    return awaiting;
}

In this version the stack frame for our await_suspend is completely gone before the awaiting coroutine is resumed.


Categories:
Posted: 27th August, 2017 07:52 (UTC)
First announced.