{"id":314,"date":"2016-03-11T12:08:49","date_gmt":"2016-03-11T12:08:49","guid":{"rendered":"http:\/\/www.crazygaze.com\/blog\/?p=314"},"modified":"2016-08-24T15:46:01","modified_gmt":"2016-08-24T15:46:01","slug":"callstack-markers-boostasiodetailcall_stack","status":"publish","type":"post","link":"https:\/\/www.crazygaze.com\/blog\/2016\/03\/11\/callstack-markers-boostasiodetailcall_stack\/","title":{"rendered":"Callstack markers (boost::asio::detail::call_stack)"},"content":{"rendered":"<p><img alt='' class='size-full wp-image-401 ' style='float: left;' src='https:\/\/www.crazygaze.com\/blog\/wp-content\/uploads\/2016\/03\/img_56e215277bbe2.png' \/><\/p>\n<p>Like I mentioned a few days ago in my <a href=\"http:\/\/www.crazygaze.com\/blog\/2016\/03\/04\/boost-asio-thread-safety-and-reinventing-the-wheel\">previous post<\/a>, I&#8217;ve been working on a new network library for my pet project. The interface turned out very similar to Boost Asio. I eventually spent a while studying how Boost Asio solves some of the problems, so it influenced my interface and some of the inner workings.<\/p>\n<p>Here, I&#8217;m going to dissect a little helper class that I needed on my way to implement the equivalent to <a href=\"http:\/\/www.boost.org\/doc\/libs\/1_60_0\/doc\/html\/boost_asio\/reference\/io_service__strand.html\">boost::asio::io_service::strand<\/a>. Now, I know I can just use Boost instead of reinventing the wheel, but I already elaborated on that in the previous post.<\/p>\n<p>So, let&#8217;s meet our little friend <a href=\"http:\/\/beta.boost.org\/doc\/libs\/1_60_0\/boost\/asio\/detail\/call_stack.hpp\">boost::asio::detail::call_stack<\/a> (or my version of it), and see why you need it.<\/p>\n<p>In some situations, your code needs to know if it is executing in the context of a particular function so it can make the right decisions. You can try to solve this in a couple of different ways.<\/p>\n<p>First, consider we have the following imaginary class to helps us out with the sample code:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n\/\/ Thread safe queue (Multi-producer\/Multi-consumer)\ntemplate &lt;typename T&gt;\nstruct ThreadSafeQueue {\npublic:\n    \/\/ Add a new element\n    void push(T v);\n\n    \/\/ Retrieves an element from the queue, optionally blocking to wait for new\n    \/\/ elements if the queue is empty\n    \/\/ \\return True if an element was retrieved, false if &#039;cancel&#039; was called\n    bool pop(T&amp; v, bool wait);\n\n    \/\/ Causes any current or future calls to &#039;pop&#039; to finish with false\n    void cancel();\n};\n<\/pre>\n<h4>The problem<\/h4>\n<p>Suppose we have this class that allows us to enqueue work to be done at a later time.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nclass WorkQueue {\npublic:\n    void post(std::function&lt;void()&gt; w) {\n        m_work.push(w);\n    }\n    \/\/ Run enqueued handlers. &quot;wait&quot; causes it to keep processing work until\n    \/\/ &quot;stop&quot; is called\n    void run(bool wait) {\n        std::function&lt;void()&gt; w;\n        while (m_work.pop(w, wait)) {\n            w();\n        }\n    }\n\n    \/\/ Stops processing new work (causing &quot;run&quot; to return)\n    void stop() {\n        m_work.cancel();\n    }\n\n    \/\/ Some method that let us know if we are currently executing our run\n    \/\/ method\n    bool isInRun();\n\nprivate:\n    \/\/ Some thread safe queue...\n    ThreadSafeQueue&lt;std::function&lt;void()&gt;&gt; m_work;\n};\n\n<\/pre>\n<p>And then we have this work item, whose behavior depends if the current thread is currently executing <em>isInRun<\/em> or not.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n\/\/ Some global work queue\nWorkQueue globalWork;\n\nvoid func1() {\n    \/\/ Code needs to behave differently if executing &quot;run&quot; on the globalWork\n    \/\/ instance at the moment\n    if (globalWork.isInRun()) {\n        \/\/ ...\n    } else {\n        \/\/ ..\n    }\n}\n\nint main() {\n    globalWork.post([]() { func1(); });\n    globalWork.run(false); \/\/ Execute any currently enqueued handlers\n    return 0;\n}\n<\/pre>\n<p>How do we implement the <em>WorkQueue::isInRun()<\/em> method ?<\/p>\n<h4>The naive way<\/h4>\n<p>Maybe have a member variable tell us if we are currently inside <em>WorkQueue::run<\/em> ?  Like this&#8230;<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nclass WorkQueue {\npublic:\n    void run(bool wait) {\n        m_running++;\n        \/\/ ...\n        m_running--;\n    }\n\n    bool isInRun() const { return m_running &gt; 0; }\nprivate:\n    int m_running = 0;\n};\n<\/pre>\n<p>Why not use <em>bool m_running<\/em> instead? So we can deal with recursion. And why would <em>run<\/em> be recursive? It calls unknown code (the handlers), and that code might do all kind of things the library didn&#8217;t account for. That&#8217;s also the reason why <strong>you should never hold locks while calling unknown code<\/strong>. It&#8217;s all too easy to end up with deadlocks.<\/p>\n<p>So, is this solution usable? Not really. The only case where it would work (that I can think off), is if you only use a <em>WorkQueue<\/em> instance from one single thread. The problem is not even because <em>m_running<\/em> is unprotected.<\/p>\n<p>Examples:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n\/\/ This works correctly\nvoid test1() {\n    globalWork.post([] {        \n        func1(); \/\/ isInRun() returns true here\n    });\n\n    \/\/ isInRun() returns false here\n    func1();\n\n    \/\/ Explicitly run any handlers\n    globalWork.run(false);\n}\n\n\/\/ This doesn&#039;t work correctly\nvoid test2() {\n    \/\/ Create worker thread to process work\n    auto th = std::thread([] { globalWork.run(true); });\n\n    globalWork.post([] {\n        \/\/ isInRun() returns true here\n        func1();\n    });\n\n    \/\/ WRONG behaviour: isInRun() returns true here.\n    \/\/ Even worse, it might return true or false depending if the worker thread\n    \/\/ is already running or not\n    func1();\n\n    \/\/ shutdown worker thread\n    globalWork.stop();\n    th.join();\n}\n<\/pre>\n<h4>The one size fits all way<\/h4>\n<p>To fix this, our idea of &#8220;currently executing&#8221; needs to be tied to the thread&#8217;s callstack itself.<\/p>\n<p>How? By placing markers in the callstack as we go, with each marker linking to the previous one. By making the most recently placed marker accessible through thread local storage (TLS), we can then iterate through all the markers in the current thread:<\/p>\n<p><img alt='' class='alignnone size-full wp-image-394 ' src='https:\/\/www.crazygaze.com\/blog\/wp-content\/uploads\/2016\/03\/img_56e17dc97661f.png' \/><\/p>\n<p>This is the implementation, extremely similar to Boost&#8217;s version. Main differences are the use of the now standard <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/storage_duration\">thread_local<\/a> , and the possibility to iterate the callstack with a <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/language\/range-for\">range based for loop<\/a> .<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\ntemplate &lt;typename Key, typename Value = unsigned char&gt;\nclass Callstack {\npublic:\n    class Iterator;\n\n    class Context {\n    public:\n        Context(const Context&amp;) = delete;\n        Context&amp; operator=(const Context&amp;) = delete;\n        explicit Context(Key* k)\n            : m_key(k), m_next(Callstack&lt;Key, Value&gt;::ms_top) {\n            m_val = reinterpret_cast&lt;unsigned char*&gt;(this);\n            Callstack&lt;Key, Value&gt;::ms_top = this;\n        }\n\n        Context(Key* k, Value&amp; v)\n            : m_key(k), m_val(&amp;v), m_next(Callstack&lt;Key, Value&gt;::ms_top) {\n            Callstack&lt;Key, Value&gt;::ms_top = this;\n        }\n\n        ~Context() {\n            Callstack&lt;Key, Value&gt;::ms_top = m_next;\n        }\n\n        Key* getKey() {\n            return m_key;\n        }\n\n        Value* getValue() {\n            return m_val;\n        }\n\n    private:\n        friend class Callstack&lt;Key, Value&gt;;\n        friend class Callstack&lt;Key, Value&gt;::Iterator;\n        Key* m_key;\n        Value* m_val;\n        Context* m_next;\n    };\n\n    class Iterator {\n    public:\n        Iterator(Context* ctx) : m_ctx(ctx) {}\n        Iterator&amp; operator++() {\n            if (m_ctx)\n                m_ctx = m_ctx-&gt;m_next;\n            return *this;\n        }\n\n        bool operator!=(const Iterator&amp; other) {\n            return m_ctx != other.m_ctx;\n        }\n\n        Context* operator*() {\n            return m_ctx;\n        }\n\n    private:\n        Context* m_ctx;\n    };\n\n    \/\/ Determine if the specified owner is on the stack\n    \/\/ \\return\n    \/\/  The address of the value if present, nullptr if not present\n    static Value* contains(const Key* k) {\n        Context* elem = ms_top;\n        while (elem) {\n            if (elem-&gt;m_key == k)\n                return elem-&gt;m_val;\n            elem = elem-&gt;m_next;\n        }\n        return nullptr;\n    }\n\n    static Iterator begin() {\n        return Iterator(ms_top);\n    }\n\n    static Iterator end() {\n        return Iterator(nullptr);\n    }\n\nprivate:\n    static thread_local Context* ms_top;\n};\n\ntemplate &lt;typename Key, typename Value&gt;\ntypename thread_local Callstack&lt;Key, Value&gt;::Context*\n    Callstack&lt;Key, Value&gt;::ms_top = nullptr;\n<\/pre>\n<p>Note that it&#039;s a templated class, which means that the following types are all distinct, and have their own linked list:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nCallstack&lt;Foo&gt;\nCallstack&lt;Foo, int&gt;\nCallstack&lt;Bar&gt;\nCallstack&lt;Bar,SomeData&gt;\n<\/pre>\n<p>Advantages of this solution:<\/p>\n<ul>\n<li>Type safety. You can use whatever <em>Key\/Value<\/em> types you want<\/li>\n<li>Every <em>Key\/Value<\/em> type combination has their own linked list, and since in practice most code will only be interested in one particular <em>Key\/Value<\/em> type combination, those checks only iterate through that linked list, thus giving us sightly better performance.<\/li>\n<li>Decouples the <em>Callstack<\/em> logic from the <em>Key\/Value<\/em> types. As-in, no need to have a <em>WorkQueue::isInRun<\/em> method like it was proposed above.<\/li>\n<li>Useful for more things other than checking if we are executing a specific function. For example, you can use it to place markers with rich debug information. Then if the application detects an assert\/error, it can iterate through those markers and log context rich information instead of just a callstack.<\/li>\n<\/ul>\n<h4>Usage examples<\/h4>\n<p>How to solve problems similar to the one presented by <em>WorkQueue<\/em> mentioned above:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nstruct Foo {\n    template &lt;typename F&gt;\n    void run(F f) {\n        \/\/ Place marker in the callstack, so any called code knows we are\n        \/\/ executing &quot;run&quot; on this Foo instance\n        Callstack&lt;Foo&gt;::Context ctx(this);\n        f();\n    }\n};\n\nFoo globalFoo;\n\nvoid func1() {\n    printf(&quot;%s\\n&quot;, Callstack&lt;Foo&gt;::contains(&amp;globalFoo) ? &quot;true&quot; : &quot;false&quot;);\n}\n\nint main() {\n    func1();               \/\/ Will print &quot;false&quot;\n    globalFoo.run(func1);  \/\/ Will print &quot;true&quot;\n    return 0;\n}\n<\/pre>\n<p>How to use for logging context rich information for asserts or fatal errors (in Debug builds).<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nstruct DebugInfo {\n    int line;\n    const char* func;\n    std::string extra;\n\n    template &lt;typename... Args&gt;\n    DebugInfo(int line, const char* func, const char* fmt, Args... args)\n        : line(line), func(func) {\n        char buf[256];\n        sprintf(buf, fmt, args...);\n        extra = buf;\n    }\n};\n\n#ifdef NDEBUG\n#define MARKER(fmt, ...) ((void)0)\n#else\n#define MARKER(fmt, ...)                                         \\\n    DebugInfo dbgInfo(__LINE__, __FUNCTION__, fmt, __VA_ARGS__); \\\n    Callstack&lt;DebugInfo&gt;::Context dbgCtx(&amp;dbgInfo);\n#endif\n\nvoid fatalError() {\n    printf(&quot;Something really bad happened.\\n&quot;);\n    printf(&quot;What we were doing...\\n&quot;);\n    for (auto ctx : Callstack&lt;DebugInfo&gt;())\n        printf(&quot;%s: %s\\n&quot;, ctx-&gt;getKey()-&gt;func, ctx-&gt;getKey()-&gt;extra.c_str());\n    exit(1);  \/\/ Kill the process\n}\n\nvoid func2(int a) {\n    MARKER(&quot;Doing something really useful with %d&quot;, a);\n    \/\/ .. Insert lots of useful code ...\n\n    \/\/ Something went wrong, lets trigger a fatal error\n    fatalError();\n}\n\nvoid func1(int a, const char* b) {\n    MARKER(&quot;Doing something really useful with %d,%s&quot;, a, b);\n    \/\/ .. Insert lots of useful code ...\n    func2(100);\n}\n\nint main() {\n    func1(1, &quot;Crazygaze&quot;);\n    return 0;\n}\n\n<\/pre>\n<p>Note that in this case the debug information placed in the stack doesn&#8217;t need to be anything related to the stack itself. You can make it as rich as you want, instead of the usual LINE\/FUNCTION information.<\/p>\n<p>In the next post, I&#8217;ll be dissecting my own variation of <a href=\"http:\/\/www.boost.org\/doc\/libs\/1_60_0\/doc\/html\/boost_asio\/reference\/io_service__strand.html\">boost::asio::io_service::strand<\/a> , which of course makes use of this <em>Callstack<\/em> class.<\/p>\n<h3>License<\/h3>\n<p>The source code in this article is licensed under the <a href=\"https:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/\">CC0 license<\/a>, so feel free to copy, modify, share, do whatever you want with it.<br \/>\nNo attribution is required, but I&#8217;ll be happy if you do.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Like I mentioned a few days ago in my previous post, I&#8217;ve been working on a new network library for my pet project. The interface turned out very similar to Boost Asio. I eventually spent a while studying how Boost Asio solves some of the problems, so it influenced my interface and some of the [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"spay_email":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true},"categories":[50],"tags":[14,12,45,10],"jetpack_featured_media_url":"","jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p7jpe0-54","_links":{"self":[{"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/posts\/314"}],"collection":[{"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/comments?post=314"}],"version-history":[{"count":1,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/posts\/314\/revisions"}],"predecessor-version":[{"id":737,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/posts\/314\/revisions\/737"}],"wp:attachment":[{"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/media?parent=314"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/categories?post=314"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.crazygaze.com\/blog\/wp-json\/wp\/v2\/tags?post=314"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}