{"id":21274169,"url":"https://github.com/endurodave/asyncmulticastdelegatecpp17","last_synced_at":"2026-02-09T09:05:16.654Z","repository":{"id":113549487,"uuid":"583970961","full_name":"endurodave/AsyncMulticastDelegateCpp17","owner":"endurodave","description":"Asynchronous Multicast Delegates in C++17","archived":false,"fork":false,"pushed_at":"2025-02-18T18:17:04.000Z","size":756,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-08-19T13:41:58.447Z","etag":null,"topics":["asynchronous-callbacks","asynchronous-function-calling","asynchronous-programming","cpp","cpp17","cross-platform","delegates","embedded-systems","linux","multi-thread","multicast","publish-subscribe","windows"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/endurodave.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-12-31T17:44:04.000Z","updated_at":"2025-02-18T18:17:08.000Z","dependencies_parsed_at":null,"dependency_job_id":"32a967d1-3e99-4340-9adc-9c09645db3d5","html_url":"https://github.com/endurodave/AsyncMulticastDelegateCpp17","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/endurodave/AsyncMulticastDelegateCpp17","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/endurodave%2FAsyncMulticastDelegateCpp17","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/endurodave%2FAsyncMulticastDelegateCpp17/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/endurodave%2FAsyncMulticastDelegateCpp17/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/endurodave%2FAsyncMulticastDelegateCpp17/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/endurodave","download_url":"https://codeload.github.com/endurodave/AsyncMulticastDelegateCpp17/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/endurodave%2FAsyncMulticastDelegateCpp17/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29260426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-09T04:11:57.159Z","status":"ssl_error","status_checked_at":"2026-02-09T04:11:56.117Z","response_time":56,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asynchronous-callbacks","asynchronous-function-calling","asynchronous-programming","cpp","cpp17","cross-platform","delegates","embedded-systems","linux","multi-thread","multicast","publish-subscribe","windows"],"created_at":"2024-11-21T09:19:13.336Z","updated_at":"2026-02-09T09:05:16.634Z","avatar_url":"https://github.com/endurodave.png","language":"C++","readme":"# Asynchronous Multicast Delegates in C++17\n\nA C++ standards compliant delegate library capable of targeting any callable function synchronously or asynchronously.\n\n## ⚠️ Deprecated Repository\n\n\u003e **Warning:** This repository is no longer maintained. Please use the modern delegate library in link below.\n\n## New Repository \n\n[DelegateMQ](https://github.com/endurodave/DelegateMQ) - Invoke any C++ callable function synchronously, asynchronously, or on a remote endpoint.\n\n# Table of Contents\n\n- [Asynchronous Multicast Delegates in C++17](#asynchronous-multicast-delegates-in-c17)\n  - [⚠️ Deprecated Repository](#️-deprecated-repository)\n  - [New Repository](#new-repository)\n- [Table of Contents](#table-of-contents)\n- [Preface](#preface)\n  - [Related Repositories](#related-repositories)\n  - [Library Comparison](#library-comparison)\n- [Introduction](#introduction)\n- [Delegates Background](#delegates-background)\n- [Quick Start](#quick-start)\n  - [Publisher](#publisher)\n  - [Subscriber](#subscriber)\n- [Project Build](#project-build)\n  - [Windows Visual Studio](#windows-visual-studio)\n  - [Linux Make](#linux-make)\n- [Using the Code](#using-the-code)\n  - [Synchronous Delegates](#synchronous-delegates)\n  - [Asynchronous Non-Blocking Delegates](#asynchronous-non-blocking-delegates)\n  - [Bind to std::shared\\_ptr](#bind-to-stdshared_ptr)\n  - [Caution Using Raw Object Pointers](#caution-using-raw-object-pointers)\n  - [Asynchronous Blocking Delegates](#asynchronous-blocking-delegates)\n  - [Asynchronous Lambda Invocation](#asynchronous-lambda-invocation)\n- [Delegate Library](#delegate-library)\n  - [Worker Thread (std::thread)](#worker-thread-stdthread)\n- [Delegate Containers](#delegate-containers)\n- [Examples](#examples)\n  - [SysData Example](#sysdata-example)\n  - [SysDataClient Example](#sysdataclient-example)\n  - [SysDataNoLock Example](#sysdatanolock-example)\n  - [SysDataNoLock Reinvoke Example](#sysdatanolock-reinvoke-example)\n  - [SysDataNoLock Blocking Reinvoke Example](#sysdatanolock-blocking-reinvoke-example)\n  - [Timer Example](#timer-example)\n- [Summary](#summary)\n- [Which Callback Implementation?](#which-callback-implementation)\n  - [Asynchronous Multicast Callbacks in C](#asynchronous-multicast-callbacks-in-c)\n  - [Asynchronous Multicast Callbacks with Inter-Thread Messaging](#asynchronous-multicast-callbacks-with-inter-thread-messaging)\n  - [Asynchronous Multicast Delegates in C++](#asynchronous-multicast-delegates-in-c)\n  - [Asynchronous Multicast Delegates in Modern C++](#asynchronous-multicast-delegates-in-modern-c)\n- [Limitations](#limitations)\n- [References](#references)\n- [Conclusion](#conclusion)\n\n\n# Preface\n\n## Related Repositories\n\n* \u003ca href=\"https://github.com/endurodave/AsyncStateMachine\"\u003eAsynchronous State Machine Design in C++\u003c/a\u003e - an asynchronous C++ state machine implemented using an asynchronous delegate library.\n* \u003ca href=\"https://github.com/endurodave/IntegrationTestFramework\"\u003eIntegration Test Framework using Google Test and Delegates\u003c/a\u003e - a multi-threaded C++ software integration test framework using Google Test and Delegate libraries.\n\n## Library Comparison\n\n\u003cp\u003eAsynchronous function invocation allows for easy movement of data between threads. The table below summarizes the various asynchronous function invocation implementations available in C and C++.\u003c/p\u003e\n\n| Repository                                                                                            | Language | Key Delegate Features                                                                                                                                                                                                               | Notes                                                                                                                                                                                                      |\n|-------------------------------------------------------------------------------------------------------|----------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegateModern\"\u003eAsyncMulticastDelegateModern\u003c/a\u003e | C++17    | * Function-like template syntax\u003cbr\u003e * Any delegate target function type (member, static, free, lambda)\u003cbr\u003e  * N target function arguments\u003cbr\u003e * N delegate subscribers\u003cbr\u003e * Variadic templates\u003cbr\u003e * Template metaprogramming      | * Most generic implementation\u003cbr\u003e * Lowest lines of source code\u003cbr\u003e * Slowest of all implementations\u003cbr\u003e * Optional fixed block allocator support\u003cbr\u003e * No remote delegate support\u003cbr\u003e * Complex metaprogramming |\n| \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegateCpp17\"\u003eAsyncMulticastDelegateCpp17\u003c/a\u003e   | C++17    | * Function-like template syntax\u003cbr\u003e * Any delegate target function type (member, static, free, lambda)\u003cbr\u003e * 5 target function arguments\u003cbr\u003e * N delegate subscribers\u003cbr\u003e * Optional fixed block allocator\u003cbr\u003e * Variadic templates | * Selective compile using constexpr\u003cbr\u003e * Avoids complex metaprogramming\u003cbr\u003e * Faster than AsyncMulticastDelegateModern\u003cbr\u003e * No remote delegate support                                                   |\n| \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegateCpp11\"\u003eAsyncMulticastDelegateCpp11\u003c/a\u003e   | C++11    | * Function-like template syntax\u003cbr\u003e * Any delegate target function type (member, static, free, lambda)\u003cbr\u003e * 5 target function arguments\u003cbr\u003e * N delegate subscribers\u003cbr\u003e * Optional fixed block allocator                          | * High lines of source code\u003cbr\u003e * Highly repetitive source code                                                                                                                                            |\n| \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegate\"\u003eAsyncMulticastDelegate\u003c/a\u003e             | C++03    | * Traditional template syntax\u003cbr\u003e * Any delegate target function type (member, static, free)\u003cbr\u003e * 5 target function arguments\u003cbr\u003e * N delegate subscribers\u003cbr\u003e * Optional fixed block allocator                                    | * High lines of source code\u003cbr\u003e * Highly repetitive source code                                                                                                                                            |\n| \u003ca href=\"https://github.com/endurodave/AsyncCallback\"\u003eAsyncCallback\u003c/a\u003e                               | C++      | * Traditional template syntax\u003cbr\u003e * Delegate target function type (static, free)\u003cbr\u003e * 1 target function argument\u003cbr\u003e * N delegate subscribers                                                                                      | * Low lines of source code\u003cbr\u003e * Most compact C++ implementation\u003cbr\u003e * Any C++ compiler                                                                                                                    |\n| \u003ca href=\"https://github.com/endurodave/C_AsyncCallback\"\u003eC_AsyncCallback\u003c/a\u003e                           | C        | * Macros provide type-safety\u003cbr\u003e * Delegate target function type (static, free)\u003cbr\u003e * 1 target function argument\u003cbr\u003e * Fixed delegate subscribers (set at compile time)\u003cbr\u003e * Optional fixed block allocator                        | * Low lines of source code\u003cbr\u003e * Very compact implementation\u003cbr\u003e * Any C compiler                                                                                                                          |\n\n\u003cp\u003eThis article documents a modern C++ implementation of asynchronous delegates. The library implements anonymous synchronous and asynchronous function callbacks. The target function is invoked with all arguments on the registrar\u0026#39;s desired thread of control.\u003c/p\u003e\n\n# Introduction\n\n\u003cp\u003eNothing seems to garner the interest of C++ programmers more than delegates. In other languages, the delegate is a first-class feature so developers can use these well-understood constructs. In C++, however, a delegate is not natively available. Yet that doesn\u0026rsquo;t stop us programmers from trying to emulate the ease with which a delegate stores and invokes any callable function.\u003c/p\u003e\n\n\u003cp\u003eDelegates normally support synchronous executions, that is, when invoked; the bound function is executed within the caller\u0026rsquo;s thread of control. On multi-threaded applications, it would be ideal to specify the target function and the thread it should execute on without imposing function signature limitations. The library does the grunt work of getting the delegate and all argument data onto the destination thread. The idea behind this article is to provide a C++ delegate library with a consistent API that is capable of synchronous and asynchronous invocations on any callable function.\u003c/p\u003e\n\n\u003cp\u003eThe features of the modern C++ delegate library are:\u003c/p\u003e\n\n\u003col\u003e\n\t\u003cli\u003e\u003cstrong\u003eAny Compiler\u003c/strong\u003e \u0026ndash; standard C++17 code for any compiler without weird hacks\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eAny Function\u003c/strong\u003e \u0026ndash; invoke any callable function: member, static, or free\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eAny Argument Type\u003c/strong\u003e \u0026ndash; supports any argument type: value, reference, pointer, pointer to pointer\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eMultiple Arguments\u003c/strong\u003e \u0026ndash; supports 5 number of function arguments for the bound function\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eSynchronous Invocation\u003c/strong\u003e \u0026ndash; call the bound function synchronously\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eAsynchronous Invocation\u003c/strong\u003e \u0026ndash; call the bound function asynchronously on a client specified thread\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eBlocking Asynchronous Invocation\u003c/strong\u003e - invoke asynchronously using blocking or non-blocking delegates\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eSmart Pointer Support\u003c/strong\u003e - bind an instance function using a raw object pointer or \u003ccode\u003estd::shared_ptr\u003c/code\u003e\u003c/li\u003e\n    \u003cli\u003e\u003cstrong\u003eLambda Support\u003c/strong\u003e - bind and invoke lambda functions asynchronously using delegates.\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eAutomatic Heap Handling\u003c/strong\u003e \u0026ndash; automatically copy argument data to the heap for safe transport through a message queue\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eAny OS\u003c/strong\u003e \u0026ndash; easy porting to any OS. C++11 \u003ccode\u003estd::thread\u003c/code\u003e port included\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eCMake\u003c/strong\u003e - CMake supports most toolchains including Windows and Linux.\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eUnit Tests\u003c/strong\u003e - extensive unit testing of the delegate library included\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eNo External Libraries\u003c/strong\u003e \u0026ndash; delegate does not rely upon external libraries\u003c/li\u003e\n\t\u003cli\u003e\u003cstrong\u003eEase of Use\u003c/strong\u003e \u0026ndash; function signature template arguments (e.g., \u003ccode\u003eMulticastDelegate\u0026lt;void(TestStruct*)\u0026gt;\u003c/code\u003e)\u003c/li\u003e\n\u003c/ol\u003e\n\n\u003cp\u003eThe delegate implementation significantly eases multithreaded application development by executing the delegate function with all of the function arguments on the thread of control that you specify. The framework handles all of the low-level machinery to safely invoke any function signature on a target thread. Windows 2017 and Eclipse projects are included for easy experimentation.\u003c/p\u003e\n\n# Delegates Background\n\n\u003cp\u003eIf you\u0026rsquo;re not familiar with a delegate, the concept is quite simple. A delegate can be thought of as a super function pointer. In C++, there\u0026#39;s no pointer type capable of pointing to all the possible function variations: instance member, virtual, const, static, and free (global). A function pointer can\u0026rsquo;t point to instance member functions, and pointers to member functions have all sorts of limitations. However, delegate classes can, in a type-safe way, point to any function provided the function signature matches. In short, a delegate points to any function with a matching signature to support anonymous function invocation.\u003c/p\u003e\n\n\u003cp\u003eIn practice, while a delegate is useful, a multicast version significantly expands its utility. The ability to bind more than one function pointer and sequentially invoke all registrars\u0026rsquo; makes for an effective publisher/subscriber mechanism. Publisher code exposes a delegate container and one or more anonymous subscribers register with the publisher for callback notifications.\u003c/p\u003e\n\n\u003cp\u003eThe problem with callbacks on a multithreaded system, whether it be a delegate-based or function pointer based, is that the callback occurs synchronously. Care must be taken that a callback from another thread of control is not invoked on code that isn\u0026rsquo;t thread-safe. Multithreaded application development is hard. It\u0026#39;s hard for the original designer; it\u0026#39;s hard because engineers of various skill levels must maintain the code; it\u0026#39;s hard because bugs manifest themselves in difficult ways. Ideally, an architectural solution helps to minimize errors and eases application development.\u003c/p\u003e\n\n\u003cp\u003eThis C++ delegate implementation is full featured and allows calling any function, even instance member functions, with any arguments either synchronously or asynchronously. The delegate library makes binding to and invoking any function a snap.\u003c/p\u003e\n\n# Quick Start\n\nA simple publish/subscribe asynchronous delegate example.\n\n## Publisher\n\nTypically a delegate is inserted into a delegate container. \u003ccode\u003eAlarmCd\u003c/code\u003e is a delegate container. \n\n\u003cfigure\u003e\n    \u003cimg src=\"Figure1.jpg\" alt=\"Figure 1\" style=\"width:65%;\"\u003e\n    \u003cfigcaption\u003eFigure 1: AlarmCb Delegate Container\u003c/figcaption\u003e\n\u003c/figure\u003e\n\n\u003cp\u003e\u003c/p\u003e\n\n1. \u003ccode\u003eMulticastDelegateSafe\u003c/code\u003e - the delegate container type.\n2. \u003ccode\u003evoid(int, const string\u0026)\u003c/code\u003e - the function signature accepted by the delegate container. Any function matching can be inserted, such as a class member, static or lambda function.\n3. \u003ccode\u003eAlarmCb\u003c/code\u003e - the delegate container name. \n\n\u003cp\u003eInvoke delegate container to notify subscribers.\u003c/p\u003e\n\n```cpp\nMulticastDelegateSafe\u003cvoid(int, const string\u0026)\u003e AlarmCb;\n\nvoid NotifyAlarmSubscribers(int alarmId, const string\u0026 note)\n{\n    // Invoke delegate to generate callback(s) to subscribers\n    AlarmCb(alarmId, note);\n}\n```\n## Subscriber\n\n\u003cp\u003eTypically a subscriber registers with a delegate container instance to receive callbacks, either synchronously or asynchronously.\u003c/p\u003e\n\n\u003cfigure\u003e\n    \u003cimg src=\"Figure2.jpg\" alt=\"Figure 2\" style=\"width:75%;\"\u003e\n    \u003cfigcaption\u003eFigure 2: Insert into AlarmCb Delegate Container\u003c/figcaption\u003e\n\u003c/figure\u003e\n\n\u003cp\u003e\u003c/p\u003e\n\n1. \u003ccode\u003eAlarmCb\u003c/code\u003e - the publisher delegate container instance.\n2. \u003ccode\u003e+=\u003c/code\u003e - add a function target to the container. \n3. \u003ccode\u003eMakeDelegate\u003c/code\u003e - creates a delegate instance.\n4. \u003ccode\u003e\u0026alarmSub\u003c/code\u003e - the subscriber object pointer.\n5. \u003ccode\u003e\u0026AlarmSub::MemberAlarmCb\u003c/code\u003e - the subscriber callback member function.\n6. \u003ccode\u003eworkerThread1\u003c/code\u003e - the thread the callback will be invoked on. Adding a thread argument changes the callback type from synchronous to asynchronous.\n\n\u003cp\u003eCreate a function conforming to the delegate signature. Insert a callable functions into the delegate container.\u003c/p\u003e\n\n```cpp\nclass AlarmSub\n{\n    void AlarmSub()\n    {\n        // Register to receive callbacks on workerThread1\n        AlarmCb += MakeDelegate(this, \u0026AlarmSub::HandleAlarmCb, workerThread1);\n    }\n\n    void ~AlarmSub()\n    {\n        // Unregister from callbacks\n        AlarmCb -= MakeDelegate(this, \u0026AlarmSub::HandleAlarmCb, workerThread1);\n    }\n\n    void HandleAlarmCb(int alarmId, const string\u0026 note)\n    {\n        // Handle callback here. Called on workerThread1 context.\n    }\n}\n```\n\n\u003cp\u003eThis is a simple example. Many other usage patterns exist including asynchronous API's, blocking delegates with a timeout, and more.\u003c/p\u003e\n\n# Project Build\n\n\u003ca href=\"https://www.cmake.org\"\u003eCMake\u003c/a\u003e is used to create the build files. CMake is free and open-source software. Windows, Linux and other toolchains are supported. Example CMake console commands executed inside the project root directory: \n\n## Windows Visual Studio\n\n\u003ccode\u003ecmake -G \"Visual Studio 17 2022\" -A Win32 -B ../AsyncMulticastDelegateCpp17Build -S .\u003c/code\u003e\n\n\u003ccode\u003ecmake -G \"Visual Studio 17 2022\" -A x64 -B ../AsyncMulticastDelegateCpp17Build -S .\u003c/code\u003e\n\n\u003ccode\u003ecmake -G \"Visual Studio 17 2022\" -A x64 -B ../AsyncMulticastDelegateCpp17Build -S . -DENABLE_UNIT_TESTS=ON\u003c/code\u003e\n\nAfter executed, open the Visual Studio project from within the \u003ccode\u003eAsyncMulticastDelegateCpp17Build\u003c/code\u003e directory.\n\n\u003cfigure\u003e\n    \u003cimg src=\"Figure3.jpg\" alt=\"Figure 3\" style=\"width:100%;\"\u003e\n    \u003cfigcaption\u003eFigure 3: Visual Studio Build\u003c/figcaption\u003e\n\u003c/figure\u003e\n\n## Linux Make\n\n\u003ccode\u003ecmake -G \"Unix Makefiles\" -B ../AsyncMulticastDelegateCpp17Build -S .\u003c/code\u003e\n\n\u003ccode\u003ecmake -G \"Unix Makefiles\" -B ../AsyncMulticastDelegateCpp17Build -S . -DENABLE_UNIT_TESTS=ON\u003c/code\u003e\n\nAfter executed, build the software from within the AsyncMulticastDelegateCpp17Build directory using the command \u003ccode\u003emake\u003c/code\u003e. Run the console app using \u003ccode\u003e./DelegateApp\u003c/code\u003e.\n\n\u003cfigure\u003e\n    \u003cimg src=\"Figure4.jpg\" alt=\"Figure 4\" style=\"width:70%;\"\u003e\n    \u003cfigcaption\u003eFigure 4: Linux Makefile Build\u003c/figcaption\u003e\n\u003c/figure\u003e\n\n# Using the Code\n\n\u003cp\u003eI\u0026rsquo;ll first present how to use the code, and then get into the implementation details.\u003c/p\u003e\n\n\u003cp\u003eThe delegate library is comprised of delegates and delegate containers. A delegate is capable of binding to a single callable function. A multicast delegate container holds one or more delegates in a list to be invoked sequentially. A single cast delegate container holds at most one delegate.\u003c/p\u003e\n\n\u003cp\u003eThe primary delegate classes are listed below:\u003c/p\u003e\n\n\u003cul class=\"class\"\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateFree\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateFreeAsync\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateFreeAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateMember\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateMemberAsync\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateMemberAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateMemberSp\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eDelegateMemberSpAsync\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cp\u003e\u003ccode\u003eDelegateFree\u0026lt;\u0026gt;\u003c/code\u003e binds to a free or static member function. \u003ccode\u003eDelegateMember\u0026lt;\u0026gt; \u003c/code\u003ebinds to a class instance member function. \u003ccode\u003eDelegateMemberSp\u0026lt;\u0026gt;\u003c/code\u003e binds to a class instance member function using a \u003ccode\u003estd::shared_ptr\u003c/code\u003e instead of a raw object pointer. All versions offer synchronous function invocation.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eDelegateFreeAsync\u0026lt;\u0026gt;\u003c/code\u003e, \u003ccode\u003eDelegateMemberAsync\u0026lt;\u0026gt;\u003c/code\u003e and \u003ccode\u003eDelegateMemberSpAsync\u0026lt;\u0026gt;\u003c/code\u003e operate in the same way as their synchronous counterparts; except these versions offer non-blocking asynchronous function execution on a specified thread of control.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eDelegateFreeAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e and \u003ccode\u003eDelegateMemberAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e provides blocking asynchronous function execution on a target thread with a caller supplied maximum wait timeout.\u003c/p\u003e\n\n\u003cp\u003eThe three main delegate container classes are:\u003c/p\u003e\n\n\u003cul class=\"class\"\u003e\n\t\u003cli\u003e\u003ccode\u003eSinglecastDelegate\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eMulticastDelegate\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003e\u003ccode\u003eMulticastDelegateSafe\u0026lt;\u0026gt;\u003c/code\u003e\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cp\u003e\u003ccode\u003eSinglecastDelegate\u0026lt;\u0026gt;\u003c/code\u003e is a delegate container accepting a single delegate. The advantage of the single cast version is that it is slightly smaller and allows a return type other than \u003ccode\u003evoid\u003c/code\u003e in the bound function.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eMulticastDelegate\u0026lt;\u0026gt;\u003c/code\u003e is a delegate container implemented as a singly-linked list accepting multiple delegates. Only a delegate bound to a function with a \u003ccode\u003evoid\u003c/code\u003e return type may be added to a multicast delegate container.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eMultcastDelegateSafe\u0026lt;\u0026gt;\u003c/code\u003e is a thread-safe container implemented as a singly-linked list accepting multiple delegates. Always use the thread-safe version if multiple threads access the container instance.\u003c/p\u003e\n\n\u003cp\u003eEach container stores the delegate by value. This means the delegate is copied internally into either heap or fixed block memory depending on the mode. The user is not required to manually create a delegate on the heap before insertion into the container. Typically, the overloaded template function \u003ccode\u003eMakeDelegate() \u003c/code\u003eis used to create a delegate instance based upon the function arguments.\u003c/p\u003e\n\n## Synchronous Delegates\n\n\u003cp\u003eAll delegates are created with the overloaded \u003ccode\u003eMakeDelegate()\u003c/code\u003e template function. The compiler uses template argument deduction to select the correct \u003ccode\u003eMakeDelegate()\u003c/code\u003e version eliminating the need to manually specify the template arguments. For example, here is a simple free function.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid FreeFuncInt(int value)\n{\n      cout \u0026lt;\u0026lt; \u0026quot;FreeCallback \u0026quot; \u0026lt;\u0026lt; value \u0026lt;\u0026lt; endl;\n}\u003c/pre\u003e\n\n\u003cp\u003eTo bind the free function to a delegate, create a \u003ccode\u003eDelegateFree\u0026lt;void(int)\u0026gt;\u003c/code\u003e instance using \u003ccode\u003eMakeDelegate()\u003c/code\u003e. The \u003ccode\u003eDelegateFree \u003c/code\u003etemplate argument is the complete function\u0026#39;s signature: \u003ccode\u003evoid(int)\u003c/code\u003e. \u003ccode\u003eMakeDelegate()\u003c/code\u003e returns a \u003ccode\u003eDelegateFree\u0026lt;void(int)\u0026gt;\u003c/code\u003e object and the following line invokes the function \u003ccode\u003eFreeFuncInt\u003c/code\u003e using the delegate.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Create a delegate bound to a free function then invoke\nDelegateFree\u0026lt;void(int)\u0026gt; delegateFree = MakeDelegate(\u0026amp;FreeFuncInt);\ndelegateFree(123);\u003c/pre\u003e\n\n\u003cp\u003eA member function is bound to a delegate in the same way, only this time \u003ccode\u003eMakeDelegate()\u003c/code\u003e uses two arguments: a class instance and a member function pointer. The two \u003ccode\u003eDelegateMember \u003c/code\u003etemplate arguments are the class name (i.e., \u003ccode\u003eTestClass\u003c/code\u003e) and the bound function signature (i.e. \u003ccode\u003evoid(TestStruct*)\u003c/code\u003e).\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Create a delegate bound to a member function then invoke    \nDelegateMember\u0026lt;TestClass, void(TestStruct*)\u0026gt; delegateMember = \n      MakeDelegate(\u0026amp;testClass, \u0026amp;TestClass::MemberFunc);    \ndelegateMember(\u0026amp;testStruct);\u003c/pre\u003e\n\n\u003cp\u003eRather than create a concrete free or member delegate, typically a delegate container is used to hold one or more delegates. A delegate container can hold any delegate type. For example, a multicast delegate container that binds to any function with a \u003ccode\u003evoid (int)\u003c/code\u003e function signature is shown below:\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegate\u0026lt;void(int)\u0026gt; delegateA;\u003c/pre\u003e\n\n\u003cp\u003eA single cast delegate is created in the same way:\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSinglecastDelegate\u0026lt;void(int)\u0026gt; delegateB;\u003c/pre\u003e\n\n\u003cp\u003eA function signature that returns a value is also possible. The delegate container accepts functions with one \u003ccode\u003efloat \u003c/code\u003eargument and returns an \u003ccode\u003eint\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSinglecastDelegate\u0026lt;int(float)\u0026gt; delegateC;\u003c/pre\u003e\n\n\u003cp\u003eA \u003ccode\u003eSinglecastDelegate\u0026lt;\u0026gt;\u003c/code\u003e may bind to a function that returns a value whereas a multicast versions cannot. The reason is that when multiple callbacks are invoked, which callback function return value should be used? The correct answer is none, so multicast containers only accept delegates with function signatures using \u003ccode\u003evoid \u003c/code\u003eas the return type.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eMulticastDelegate \u003c/code\u003econtainers bind to one or more functions.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegate\u0026lt;void(int, int)\u0026gt; delegateD;\n\nMulticastDelegate\u0026lt;void(float, int, char)\u0026gt; delegateE;\u003c/pre\u003e\n\n\u003cp\u003eOf course, more than just built-in pass by value argument types are supported.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegate\u0026lt;void(const MyClass\u0026amp;, MyStruct*, Data**)\u0026gt; delegateF;\u003c/pre\u003e\n\n\u003cp\u003eCreating a delegate instance and adding it to the multicast delegate container is accomplished with the overloaded \u003ccode\u003eMakeDelegate()\u003c/code\u003e function and \u003ccode\u003eoperator+=\u003c/code\u003e. Binding a free function or \u003ccode\u003estatic\u003c/code\u003e function only requires a single function pointer argument.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateA += MakeDelegate(\u0026amp;FreeFuncInt);\u003c/pre\u003e\n\n\u003cp\u003eAn instance member function can also be added to any delegate container. For member functions, the first argument to \u003ccode\u003eMakeDelegate()\u003c/code\u003e is a pointer to the class instance. The second argument is a pointer to the member function.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateA += MakeDelegate(\u0026amp;testClass, \u0026amp;TestClass::MemberFunc);\u003c/pre\u003e\n\n\u003cp\u003eCheck for registered clients first, and then invoke callbacks for all registered delegates. If multiple delegates are stored within \u003ccode\u003eMulticastDelegate\u0026lt;void(int)\u0026gt;\u003c/code\u003e, each one is called sequentially.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Invoke the delegate target functions\nif (delegateA)\n      delegateA(123);\u003c/pre\u003e\n\n\u003cp\u003eRemoving a delegate instance from the delegate container uses \u003ccode\u003eoperator-=\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateA -= MakeDelegate(\u0026amp;FreeFuncInt);\u003c/pre\u003e\n\n\u003cp\u003eAlternatively, \u003ccode\u003eClear()\u003c/code\u003e is used to remove all delegates within the container.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateA.Clear();\u003c/pre\u003e\n\n\u003cp\u003eA delegate is added to the single cast container using \u003ccode\u003eoperator=\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSinglecastDelegate\u0026lt;int(int)\u0026gt; delegateF;\ndelegateF = MakeDelegate(\u0026amp;FreeFuncIntRetInt);\u003c/pre\u003e\n\n\u003cp\u003eRemoval is with \u003ccode\u003eClear()\u003c/code\u003e or assigning \u003ccode\u003e0\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateF.Clear();\ndelegateF = 0;\u003c/pre\u003e\n\n## Asynchronous Non-Blocking Delegates\n\n\u003cp\u003eUp until this point, the delegates have all been synchronous. The asynchronous features are layered on top of the synchronous delegate implementation. To use asynchronous delegates, a thread-safe delegate container safely accessible by multiple threads is required. Locks protect the class API against simultaneous access. The \u0026ldquo;\u003ccode\u003eSafe\u003c/code\u003e\u0026rdquo; version is shown below.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegateSafe\u0026lt;void(TestStruct*)\u0026gt; delegateC;\u003c/pre\u003e\n\n\u003cp\u003eA thread pointer as the last argument to \u003ccode\u003eMakeDelegate()\u003c/code\u003e forces creation of an asynchronous delegate. In this case, adding a thread argument causes \u003ccode\u003eMakeDelegate()\u003c/code\u003e to return a \u003ccode\u003eDelegateMemberAsync\u0026lt;\u0026gt;\u003c/code\u003e as opposed to \u003ccode\u003eDelegateMember\u0026lt;\u0026gt;\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ndelegateC += MakeDelegate(\u0026amp;testClass, \u0026amp;TestClass::MemberFunc, workerThread1);\u003c/pre\u003e\n\n\u003cp\u003eInvocation is the same as the synchronous version, yet this time the callback function \u003ccode\u003eTestClass::MemberFunc()\u003c/code\u003e is called from \u003ccode\u003eworkerThread1\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nif (delegateC)\n      delegateC(\u0026amp;testStruct);\u003c/pre\u003e\n\n\u003cp\u003eHere is another example of an asynchronous delegate being invoked on \u003ccode\u003eworkerThread1 \u003c/code\u003ewith \u003ccode\u003estd::string\u003c/code\u003e and \u003ccode\u003eint \u003c/code\u003earguments.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Create delegate with std::string and int arguments then asynchronously    \n// invoke on a member function\nMulticastDelegateSafe\u0026lt;void(const std::string\u0026amp;, int)\u0026gt; delegateH;\ndelegateH += MakeDelegate(\u0026amp;testClass, \u0026amp;TestClass::MemberFuncStdString, workerThread1);\ndelegateH(\u0026quot;Hello world\u0026quot;, 2020);\u003c/pre\u003e\n\n\u003cp\u003eUsage of the library is consistent between synchronous and asynchronous delegates. The only difference is the addition of a thread pointer argument to \u003ccode\u003eMakeDelegate()\u003c/code\u003e. Always remember to use the thread-safe \u003ccode\u003eMulticastDelegateSafe\u0026lt;\u0026gt;\u003c/code\u003e containers when using asynchronous delegates to callback across thread boundaries.\u003c/p\u003e\n\n\u003cp\u003eThe default behavior of the delegate library when invoking non-blocking asynchronous delegates is that arguments\u0026nbsp;are copied into heap memory for safe transport to the destination thread. This means all arguments will be duplicated. If your data is something other than plain old data (POD) and can\u0026rsquo;t be bitwise copied, then be sure to implement an appropriate copy constructor to handle the copying yourself.\u003c/p\u003e\n\n\u003cp\u003eFor more examples, see \u003cem\u003emain.cpp\u003c/em\u003e and \u003cem\u003eDelegateUnitTests.cpp\u003c/em\u003e within the attached source code.\u003c/p\u003e\n\n## Bind to std::shared_ptr\n\n\u003cp\u003eBinding to instance member function requires a pointer to an object. The delegate library supports binding with a raw pointer and a \u003ccode\u003estd::shared_ptr\u003c/code\u003e smart pointer. Usage is what you\u0026rsquo;d expect; just use a \u003ccode\u003estd::shared_ptr\u003c/code\u003e in place of the raw object pointer in the call to \u003ccode\u003eMakeDelegate()\u003c/code\u003e. Depending on if a thread argument is passed to \u003ccode\u003eMakeDelegate()\u003c/code\u003e or not, a \u003ccode\u003eDelegateMemberSp\u0026lt;\u0026gt;\u003c/code\u003e or \u003ccode\u003eDelegateMemberSpAsync\u0026lt;\u0026gt;\u003c/code\u003e instance is returned.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Create a shared_ptr, create a delegate, then synchronously invoke delegate function\nstd::shared_ptr\u0026lt;TestClass\u0026gt; spObject(new TestClass());\nauto delegateMemberSp = MakeDelegate(spObject, \u0026amp;TestClass::MemberFuncStdString);\ndelegateMemberSp(\u0026quot;Hello world using shared_ptr\u0026quot;, 2020);\u003c/pre\u003e\n\n## Caution Using Raw Object Pointers\n\n\u003cp\u003eCertain asynchronous delegate usage patterns can cause a callback invocation to occur on a deleted object. The problem is this: an object function is bound to a delegate and invoked asynchronously, but before the invocation occurs on the target thread, the target object is deleted. In other words, it is possible for an object bound to a delegate to be deleted before the target thread message queue has had a chance to invoke the callback. The following code exposes the issue:\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n    // Example of a bug where the testClassHeap is deleted before the asychronous delegate\n    // is invoked on the workerThread1. In other words, by the time workerThread1 calls\n    // the bound delegate function the testClassHeap instance is deleted and no longer valid.\n    TestClass* testClassHeap = new TestClass();\n    auto delegateMemberAsync = \n           MakeDelegate(testClassHeap, \u0026amp;TestClass::MemberFuncStdString, workerThread1);\n    delegateMemberAsync(\u0026quot;Function async invoked on deleted object. Bug!\u0026quot;, 2020);\n    delegateMemberAsync.Clear();\n    delete testClassHeap;\u003c/pre\u003e\n\n\u003cp\u003eThe example above is contrived, but it does clearly show that nothing prevents an object being deleted while waiting for the asynchronous invocation to occur. In many embedded system architectures, the registrations might occur on singleton objects or objects that have a lifetime that spans the entire execution. In this way, the application\u0026rsquo;s usage pattern prevents callbacks into deleted objects. However, if objects pop into existence, temporarily subscribe to a delegate for callbacks, then get deleted later the possibility of a latent delegate stuck in a message queue could invoke a function on a deleted object.\u003c/p\u003e\n\n\u003cp\u003eFortunately, C++ smart pointers are just the ticket to solve these complex object lifetime issues. A \u003ccode\u003eDelegateMemberSpAsync\u0026lt;\u0026gt;\u003c/code\u003e delegate binds using a \u003ccode\u003estd::shared_ptr\u003c/code\u003e instead of a raw object pointer. Now that the delegate has a shared pointer, the danger of the object being prematurely deleted is eliminated. The shared pointer will only delete the object pointed to once all references are no longer in use. In the code snippet below, all references to \u003ccode\u003etestClassSp \u003c/code\u003eare removed by the client code yet the delegate\u0026rsquo;s copy placed into the queue prevents \u003ccode\u003eTestClass \u003c/code\u003edeletion until after the asynchronous delegate callback occurs.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n    // Example of the smart pointer function version of the delegate. The testClassSp instance\n    // is only deleted after workerThread1 invokes the callback function thus solving the bug.\n    std::shared_ptr\u0026lt;TestClass\u0026gt; testClassSp(new TestClass());\n    auto delegateMemberSpAsync = MakeDelegate\n         (testClassSp, \u0026amp;TestClass::MemberFuncStdString, workerThread1);\n    delegateMemberSpAsync(\u0026quot;Function async invoked using smart pointer. Bug solved!\u0026quot;, 2020);\n    delegateMemberSpAsync.Clear();\n    testClassSp.reset();\u003c/pre\u003e\n\n\u003cp\u003eActually, this technique can be used to call an object function, and then the object automatically deletes after the callback occurs. Using the above example, create a shared pointer instance, bind a delegate, and invoke the delegate. Now \u003ccode\u003etestClassSp\u003c/code\u003e can go out of scope and \u003ccode\u003eTestClass::MemberFuncStdString\u003c/code\u003e will still be safely called on \u003ccode\u003eworkerThread1\u003c/code\u003e. The \u003ccode\u003eTestClass \u003c/code\u003einstance will delete by way of \u003ccode\u003estd::shared_ptr\u0026lt;TestClass\u0026gt;\u003c/code\u003e once the smart pointer reference count goes to 0 after the callback completes without any extra programmer involvement.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nstd::shared_ptr\u0026lt;TestClass\u0026gt; testClassSp(new TestClass());\nauto delegateMemberSpAsync =\n    MakeDelegate(testClassSp, \u0026amp;TestClass::MemberFuncStdString, workerThread1);\ndelegateMemberSpAsync(\u0026quot;testClassSp deletes after delegate invokes\u0026quot;, 2020);\u003c/pre\u003e\n\n## Asynchronous Blocking Delegates\n\n\u003cp\u003eA blocking delegate waits until the target thread executes the bound delegate function. Unlike non-blocking delegates, the blocking versions do not copy argument data onto the heap. They also allow function return types other than \u003ccode\u003evoid\u003c/code\u003e whereas the non-blocking delegates only bind to functions returning \u003ccode\u003evoid\u003c/code\u003e. Since the function arguments are passed to the destination thread unmodified, the function executes just as you\u0026#39;d expect a synchronous version including incoming/outgoing pointers and references.\u003c/p\u003e\n\n\u003cp\u003eStack arguments passed by pointer/reference need not be thread-safe. The reason is that the calling thread blocks waiting for the destination thread to complete. This means that the delegate implementation guarantees only one thread is able to access stack allocated argument data.\u003c/p\u003e\n\n\u003cp\u003eA blocking delegate must specify a timeout in milliseconds or \u003ccode\u003eWAIT_INFINITE\u003c/code\u003e. Unlike a non-blocking asynchronous delegate, which is guaranteed to be invoked, if the timeout expires on a blocking delegate, the function is not invoked. Use \u003ccode\u003eIsSuccess()\u003c/code\u003e to determine if the delegate succeeded or not.\u003c/p\u003e\n\n\u003cp\u003eAdding a timeout as the last argument to \u003ccode\u003eMakeDelegate()\u003c/code\u003e causes a \u003ccode\u003eDelegateFreeAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e or \u003ccode\u003eDelegateMemberAsyncWait\u0026lt;\u0026gt;\u003c/code\u003e instance to be returned depending on if a free or member function is being bound. A \u0026quot;\u003ccode\u003eWait\u003c/code\u003e\u0026quot; delegate is typically not added to a delegate container. The typical usage pattern is to create a delegate and function arguments on the stack, then invoke. The code fragment below creates a blocking delegate with the function signature \u003ccode\u003eint (std::string\u0026amp;\u003c/code\u003e). The function is called on \u003ccode\u003eworkerThread1\u003c/code\u003e. The function \u003ccode\u003eMemberFuncStdStringRetInt()\u003c/code\u003e will update the outgoing \u003ccode\u003estring msg\u003c/code\u003e and return an integer to the caller.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n    // Create a asynchronous blocking delegate and invoke. This thread will block until the\n    // msg and year stack values are set by MemberFuncStdStringRetInt on workerThread1.\n    auto delegateI = \n          MakeDelegate(\u0026amp;testClass, \u0026amp;TestClass::MemberFuncStdStringRetInt, \n                       workerThread1, WAIT_INFINITE);\n    std::string msg;\n    int year = delegateI(msg);\n    if (delegateI.IsSuccess())\n    {\n        cout \u0026lt;\u0026lt; msg.c_str() \u0026lt;\u0026lt; \u0026quot; \u0026quot; \u0026lt;\u0026lt; year \u0026lt;\u0026lt; endl;\n    }\u003c/pre\u003e\n\n## Asynchronous Lambda Invocation\n\n\u003cp\u003eDelegates can invoke non-capturing\u0026nbsp;lambda functions asynchronously. The example below calls\u0026nbsp;\u003ccode\u003eLambdaFunc1\u0026nbsp;\u003c/code\u003eon\u0026nbsp;\u003ccode\u003eworkerThread1\u003c/code\u003e.\u0026nbsp;\u003c/p\u003e\n\n\u003cpre data-allowshrink=\"True\" data-codeblock-processed=\"true\" data-collapse=\"False\" id=\"pre516246\"\u003e\nauto LambdaFunc1 = +[](int i) -\u0026gt; int\n{\n    cout \u0026lt;\u0026lt; \u0026quot;Called LambdaFunc1 \u0026quot; \u0026lt;\u0026lt; i \u0026lt;\u0026lt; std::endl;\n    return ++i;\n};\n\n// Asynchronously invoke lambda on workerThread1 and wait for the return value\nauto lambdaDelegate1 = MakeDelegate(LambdaFunc1, workerThread1, WAIT_INFINITE);\nint lambdaRetVal2 = lambdaDelegate1(123);\n\u003c/pre\u003e\n\n\u003cp\u003eDelegates are callable and therefore may be passed to the standard library. The example below shows\u0026nbsp;\u003ccode\u003eCountLambda\u0026nbsp;\u003c/code\u003eexecuted asynchronously on\u0026nbsp;\u003ccode\u003eworkerThread1\u0026nbsp;\u003c/code\u003eby\u0026nbsp;\u003ccode\u003estd::count_if\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre data-allowshrink=\"True\" data-codeblock-processed=\"true\" data-collapse=\"False\" id=\"pre407028\"\u003e\nstd::vector\u0026lt;int\u0026gt; v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n\nauto CountLambda = +[](int v) -\u0026gt; int\n{\n    return v \u0026gt; 2 \u0026amp;\u0026amp; v \u0026lt;= 6;\n};\nauto countLambdaDelegate = MakeDelegate(CountLambda, workerThread1, WAIT_INFINITE);\n\nconst auto valAsyncResult = std::count_if(v.begin(), v.end(),\n    countLambdaDelegate);\ncout \u0026lt;\u0026lt; \u0026quot;Asynchronous lambda result: \u0026quot; \u0026lt;\u0026lt; valAsyncResult \u0026lt;\u0026lt; endl;\u003c/pre\u003e\n\n# Delegate Library\n\n\u003cp\u003eThe delegate library contains numerous classes. A single include \u003cem\u003eDelegateLib.h\u003c/em\u003e provides access to all delegate library features. The library is wrapped within a \u003ccode\u003eDelegateLib \u003c/code\u003enamespace. Included unit tests help ensure a robust implementation. The table below shows the delegate class hierarchy.\u003c/p\u003e\n\n```cpp\nDelegateBase\n    Delegate\u003c\u003e\n        DelegateFree\u003c\u003e\n            DelegateFreeAsync\u003c\u003e\n                DelegateFreeAsyncWait\u003c\u003e\n        DelegateMember\u003c\u003e\n            DelegateMemberAsync\u003c\u003e\n                DelegateMemberAsyncWait\u003c\u003e\n        DelegateMemberSp\u003c\u003e\n```\n\nFor this implementation the section \"Delegate Library\" was not updated. See the section \"Delegate Library\" in both the links below for design implementation details. While some information (like code snippets) are not directly related to this implementation, the ideas and cautions are still useful. \n\n* \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegateCpp11\"\u003eAsyncMulticastDelegateCpp11\u003c/a\u003e\u003cbr\u003e\n* \u003ca href=\"https://github.com/endurodave/AsyncMulticastDelegateModern\"\u003eAsyncMulticastDelegateModern\u003c/a\u003e\u003cbr\u003e\n\n## Worker Thread (std::thread)\n\n\u003cp\u003eThe \u003ccode\u003estd::thread\u003c/code\u003e implemented thread loop is shown below. The loop calls the \u003ccode\u003eDelegateInvoke()\u003c/code\u003e\u0026nbsp;function on each asynchronous delegate instance.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid WorkerThread::Process()\n{\n    while (1)\n    {\n        std::shared_ptr\u0026lt;ThreadMsg\u0026gt; msg;\n        {\n            // Wait for a message to be added to the queue\n            std::unique_lock\u0026lt;std::mutex\u0026gt; lk(m_mutex);\n            while (m_queue.empty())\n                m_cv.wait(lk);\n\n            if (m_queue.empty())\n                continue;\n\n            msg = m_queue.front();\n            m_queue.pop();\n        }\n\n        switch (msg-\u0026gt;GetId())\n        {\n            case MSG_DISPATCH_DELEGATE:\n            {\n                ASSERT_TRUE(msg-\u0026gt;GetData() != NULL);\n\n                // Convert the ThreadMsg void* data back to a DelegateMsg* \n                auto delegateMsg = msg-\u0026gt;GetData();\n\n                // Invoke the callback on the target thread\n                delegateMsg-\u0026gt;GetDelegateInvoker()-\u0026gt;DelegateInvoke(delegateMsg);\n                break;\n            }\n\n            case MSG_EXIT_THREAD:\n            {\n                return;\n            }\n\n            default:\n                ASSERT();\n        }\n    }\n}\u003c/pre\u003e\n\n\u003cp\u003eAny project-specific thread loop can call \u003ccode\u003eDelegateInvoke()\u003c/code\u003e. This is just one example. The only requirement is that your worker thread class inherit from\u0026nbsp;\u003ccode\u003eDelegateLib::DelegateThread\u003c/code\u003e and implement the\u0026nbsp;\u003ccode\u003eDispatchDelegate()\u003c/code\u003e abstract function. \u003ccode\u003eDisplatchDelegate()\u003c/code\u003e will insert the shared message pointer into the thread queue for processing.\u0026nbsp;\u003c/p\u003e\n\n# Delegate Containers\n\n\u003cp\u003eDelegate containers store one or more delegates. The delegate container hierarchy is shown below:\u003c/p\u003e\n\n```cpp\nMulticastDelegate\u003c\u003e\n    MulticastDelegateSafe\u003c\u003e\nSinglecastDelegate\u003c\u003e\n```\n\n\u003cp\u003e\u003ccode\u003eMulticastDelegate\u0026lt;\u0026gt;\u003c/code\u003e provides the function \u003ccode\u003eoperator()\u003c/code\u003e to sequentially invoke each delegate within the list.\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003eMulticastDelegateSafe\u0026lt;\u0026gt;\u003c/code\u003e provides a thread-safe wrapper around the delegate API. Each function provides a lock guard to protect against simultaneous access. The Resource Acquisition is Initialization (RAII) technique is used for the locks.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\ntemplate \u0026lt;class R\u0026gt;\nstruct MulticastDelegateSafe; // Not defined\n\n/// @brief Thread-safe multicast delegate container class. \ntemplate\u0026lt;class RetType, class... Args\u0026gt;\nclass MulticastDelegateSafe\u0026lt;RetType(Args...)\u0026gt; : public MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;\n{\npublic:\n    MulticastDelegateSafe() { LockGuard::Create(\u0026amp;m_lock); }\n    ~MulticastDelegateSafe() { LockGuard::Destroy(\u0026amp;m_lock); }\n\n    void operator+=(const Delegate\u0026lt;RetType(Args...)\u0026gt;\u0026amp; delegate) {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::operator +=(delegate);\n    }\n    void operator-=(const Delegate\u0026lt;RetType(Args...)\u0026gt;\u0026amp; delegate) {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::operator -=(delegate);\n    }\n    void operator()(Args... args) {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::operator ()(args...);\n    }\n    bool Empty() {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        return MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::Empty();\n    }\n    void Clear() {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::Clear();\n    }\n\n    explicit operator bool() {\n        LockGuard lockGuard(\u0026amp;m_lock);\n        return MulticastDelegate\u0026lt;RetType(Args...)\u0026gt;::operator bool();\n    }\n\nprivate:\n    // Prevent copying objects\n    MulticastDelegateSafe(const MulticastDelegateSafe\u0026amp;) = delete;\n    MulticastDelegateSafe\u0026amp; operator=(const MulticastDelegateSafe\u0026amp;) = delete;\n\n    /// Lock to make the class thread-safe\n    LOCK m_lock;\n};\u003c/pre\u003e\n\n# Examples\n\n## SysData Example\n\n\u003cp\u003eA few real-world examples will demonstrate common delegate usage patterns. First, \u003ccode\u003eSysData \u003c/code\u003eis a simple class showing how to expose an outgoing asynchronous interface. The class stores system data and provides asynchronous subscriber notifications when the mode changes. The class interface is shown below:\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nclass SysData\n{\npublic:\n    /// Clients register with MulticastDelegateSafe1 to get callbacks when system mode changes\n    MulticastDelegateSafe\u0026lt;void(const SystemModeChanged\u0026amp;)\u0026gt; SystemModeChangedDelegate;\n\n    /// Get singleton instance of this class\n    static SysData\u0026amp; GetInstance();\n\n    /// Sets the system mode and notify registered clients via SystemModeChangedDelegate.\n    /// @param[in] systemMode - the new system mode. \n    void SetSystemMode(SystemMode::Type systemMode);    \n\nprivate:\n    SysData();\n    ~SysData();\n\n    /// The current system mode data\n    SystemMode::Type m_systemMode;\n\n    /// Lock to make the class thread-safe\n    LOCK m_lock;\n};\u003c/pre\u003e\n\n\u003cp\u003eThe subscriber interface for receiving callbacks is \u003ccode\u003eSystemModeChangedDelegate\u003c/code\u003e. Calling \u003ccode\u003eSetSystemMode()\u003c/code\u003e saves the new mode into \u003ccode\u003em_systemMode \u003c/code\u003eand notifies all registered subscribers.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid SysData::SetSystemMode(SystemMode::Type systemMode)\n{\n    LockGuard lockGuard(\u0026amp;m_lock);\n\n    // Create the callback data\n    SystemModeChanged callbackData;\n    callbackData.PreviousSystemMode = m_systemMode;\n    callbackData.CurrentSystemMode = systemMode;\n\n    // Update the system mode\n    m_systemMode = systemMode;\n\n    // Callback all registered subscribers\n    if (SystemModeChangedDelegate)\n        SystemModeChangedDelegate(callbackData);\n}\u003c/pre\u003e\n\n## SysDataClient Example\n\n\u003cp\u003e\u003ccode\u003eSysDataClient \u003c/code\u003eis a delegate subscriber and registers for \u003ccode\u003eSysData::SystemModeChangedDelegate\u003c/code\u003e notifications within the constructor.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n    // Constructor\n    SysDataClient() :\n        m_numberOfCallbacks(0)\n    {\n        // Register for async delegate callbacks\n        SysData::GetInstance().SystemModeChangedDelegate += \n                 MakeDelegate(this, \u0026amp;SysDataClient::CallbackFunction, workerThread1);\n        SysDataNoLock::GetInstance().SystemModeChangedDelegate += \n                       MakeDelegate(this, \u0026amp;SysDataClient::CallbackFunction, workerThread1);\n    }\u003c/pre\u003e\n\n\u003cp\u003e\u003ccode\u003eSysDataClient::CallbackFunction()\u003c/code\u003e is now called on \u003ccode\u003eworkerThread1 \u003c/code\u003ewhen the system mode changes.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n    void CallbackFunction(const SystemModeChanged\u0026amp; data)\n    {\n        m_numberOfCallbacks++;\n        cout \u0026lt;\u0026lt; \u0026quot;CallbackFunction \u0026quot; \u0026lt;\u0026lt; data.CurrentSystemMode \u0026lt;\u0026lt; endl;\n    }\u003c/pre\u003e\n\n\u003cp\u003eWhen \u003ccode\u003eSetSystemMode()\u003c/code\u003e is called, anyone interested in the mode changes are notified synchronously or asynchronously depending on the delegate type registered.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n// Set new SystemMode values. Each call will invoke callbacks to all\n// registered client subscribers.\nSysData::GetInstance().SetSystemMode(SystemMode::STARTING);\nSysData::GetInstance().SetSystemMode(SystemMode::NORMAL);\u003c/pre\u003e\n\n## SysDataNoLock Example\n\n\u003cp\u003e\u003ccode\u003eSysDataNoLock\u003c/code\u003e is an alternate implementation that uses a \u003ccode\u003eprivate\u003c/code\u003e \u003ccode\u003eMulticastDelegateSafe\u0026lt;\u0026gt;\u003c/code\u003e for setting the system mode asynchronously and without locks.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nclass SysDataNoLock\n{\npublic:\n    /// Clients register with MulticastDelegateSafe to get callbacks when system mode changes\n    MulticastDelegateSafe\u0026lt;void(const SystemModeChanged\u0026amp;)\u0026gt; SystemModeChangedDelegate;\n\n    /// Get singleton instance of this class\n    static SysDataNoLock\u0026amp; GetInstance();\n\n    /// Sets the system mode and notify registered clients via SystemModeChangedDelegate.\n    /// @param[in] systemMode - the new system mode. \n    void SetSystemMode(SystemMode::Type systemMode);    \n\n    /// Sets the system mode and notify registered clients via a temporary stack created\n    /// asynchronous delegate. \n    /// @param[in] systemMode - The new system mode. \n    void SetSystemModeAsyncAPI(SystemMode::Type systemMode);    \n\n    /// Sets the system mode and notify registered clients via a temporary stack created\n    /// asynchronous delegate. This version blocks (waits) until the delegate callback\n    /// is invoked and returns the previous system mode value. \n    /// @param[in] systemMode - The new system mode. \n    /// @return The previous system mode. \n    SystemMode::Type SetSystemModeAsyncWaitAPI(SystemMode::Type systemMode);\n\nprivate:\n    SysDataNoLock();\n    ~SysDataNoLock();\n\n    /// Private callback to get the SetSystemMode call onto a common thread\n    MulticastDelegateSafe\u0026lt;void(SystemMode::Type)\u0026gt; SetSystemModeDelegate; \n\n    /// Sets the system mode and notify registered clients via SystemModeChangedDelegate.\n    /// @param[in] systemMode - the new system mode. \n    void SetSystemModePrivate(SystemMode::Type);    \n\n    /// The current system mode data\n    SystemMode::Type m_systemMode;\n};\u003c/pre\u003e\n\n\u003cp\u003eThe constructor registers \u003ccode\u003eSetSystemModePrivate()\u003c/code\u003e with the \u003ccode\u003eprivate\u003c/code\u003e \u003ccode\u003eSetSystemModeDelegate\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSysDataNoLock::SysDataNoLock() :\n    m_systemMode(SystemMode::STARTING)\n{\n    SetSystemModeDelegate += MakeDelegate\n                 (this, \u0026amp;SysDataNoLock::SetSystemModePrivate, workerThread2);\n    workerThread2.CreateThread();\n}\u003c/pre\u003e\n\n\u003cp\u003eThe \u003ccode\u003eSetSystemMode()\u003c/code\u003e function below is an example of an asynchronous incoming interface. To the caller, it looks like a normal function, but under the hood, a private member call is invoked asynchronously using a delegate. In this case, invoking \u003ccode\u003eSetSystemModeDelegate\u003c/code\u003e causes \u003ccode\u003eSetSystemModePrivate()\u003c/code\u003e to be called on \u003ccode\u003eworkerThread2\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid SysDataNoLock::SetSystemMode(SystemMode::Type systemMode)\n{\n    // Invoke the private callback. SetSystemModePrivate() will be called on workerThread2.\n    SetSystemModeDelegate(systemMode);\n}\u003c/pre\u003e\n\n\u003cp\u003eSince this \u003ccode\u003eprivate\u003c/code\u003e function is always invoked asynchronously on \u003ccode\u003eworkerThread2\u003c/code\u003e, it doesn\u0026#39;t require locks.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid SysDataNoLock::SetSystemModePrivate(SystemMode::Type systemMode)\n{\n      // Create the callback data\n      SystemModeChanged callbackData;\n\n      callbackData.PreviousSystemMode = m_systemMode;\n      callbackData.CurrentSystemMode = systemMode;\n\n      // Update the system mode\n      m_systemMode = systemMode;\n\n      // Callback all registered subscribers\n      if (SystemModeChangedDelegate)\n            SystemModeChangedDelegate(callbackData);\n}\u003c/pre\u003e\n\n## SysDataNoLock Reinvoke Example\n\n\u003cp\u003eWhile creating a separate \u003ccode\u003eprivate\u003c/code\u003e function to create an asynchronous API does work, with delegates, it\u0026#39;s possible to just reinvoke the same exact function just on a different thread. Perform a simple check whether the caller is executing on the desired thread of control. If not, a temporary asynchronous delegate is created on the stack and then invoked. The delegate and all the caller\u0026rsquo;s original function arguments are duplicated on the heap and the function is reinvoked on \u003ccode\u003eworkerThread2\u003c/code\u003e. This is an elegant way to create asynchronous APIs with the absolute minimum of effort.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nvoid SysDataNoLock::SetSystemModeAsyncAPI(SystemMode::Type systemMode)\n{\n    // Is the caller executing on workerThread2?\n    if (workerThread2.GetThreadId() != WorkerThread::GetCurrentThreadId())\n    {\n        // Create an asynchronous delegate and re-invoke the function call on workerThread2\n        auto delegate = \n             MakeDelegate(this, \u0026amp;SysDataNoLock::SetSystemModeAsyncAPI, workerThread2);\n        delegate(systemMode);\n        return;\n    }\n\n    // Create the callback data\n    SystemModeChanged callbackData;\n    callbackData.PreviousSystemMode = m_systemMode;\n    callbackData.CurrentSystemMode = systemMode;\n\n    // Update the system mode\n    m_systemMode = systemMode;\n\n    // Callback all registered subscribers\n    if (SystemModeChangedDelegate)\n        SystemModeChangedDelegate(callbackData);\n}\u003c/pre\u003e\n\n## SysDataNoLock Blocking Reinvoke Example\n\n\u003cp\u003eA blocking asynchronous API can be hidden inside a class member function. The function below sets the current mode on \u003ccode\u003eworkerThread2 \u003c/code\u003eand returns the previous mode. A blocking delegate is created on the stack and invoked if the caller isn\u0026#39;t executing on \u003ccode\u003eworkerThread2\u003c/code\u003e. To the caller, the function appears synchronous, but the delegate ensures that the call is executed on the proper thread before returning.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSystemMode::Type SysDataNoLock::SetSystemModeAsyncWaitAPI(SystemMode::Type systemMode)\n{\n    // Is the caller executing on workerThread2?\n    if (workerThread2.GetThreadId() != WorkerThread::GetCurrentThreadId())\n    {\n        // Create an asynchronous delegate and re-invoke the function call on workerThread2\n        auto delegate =\n            MakeDelegate(this, \u0026amp;SysDataNoLock::SetSystemModeAsyncWaitAPI, \n                         workerThread2, WAIT_INFINITE);\n        return delegate(systemMode);\n    }\n\n    // Create the callback data\n    SystemModeChanged callbackData;\n    callbackData.PreviousSystemMode = m_systemMode;\n    callbackData.CurrentSystemMode = systemMode;\n\n    // Update the system mode\n    m_systemMode = systemMode;\n\n    // Callback all registered subscribers\n    if (SystemModeChangedDelegate)\n        SystemModeChangedDelegate(callbackData);\n\n    return callbackData.PreviousSystemMode;\n}\u003c/pre\u003e\n\n## Timer Example\n\n\u003cp\u003eOnce a delegate framework is in place, creating a timer callback service is trivial. Many systems need a way to generate a callback based on a timeout. Maybe it\u0026#39;s a periodic timeout for some low speed polling or maybe an error timeout in case something doesn\u0026#39;t occur within the expected time frame. Either way, the callback must occur on a specified thread of control. A \u003ccode\u003eSinglecastDelegate\u0026lt;void(void)\u0026gt; \u003c/code\u003eused inside a \u003ccode\u003eTimer\u003c/code\u003e class solves this nicely.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\n/// @brief A timer class provides periodic timer callbacks on the client\u0026#39;s\u0026nbsp;\n/// thread of control. Timer is thread safe.\nclass Timer\u0026nbsp;\n{\npublic:\n\u0026nbsp;\u0026nbsp; \u0026nbsp;static const DWORD MS_PER_TICK;\n\n\u0026nbsp;\u0026nbsp; \u0026nbsp;/// Client\u0026#39;s register with Expired to get timer callbacks\n\u0026nbsp;\u0026nbsp; \u0026nbsp;SinglecastDelegate\u0026lt;void(void)\u0026gt; Expired;\n\n\u0026nbsp;\u0026nbsp; \u0026nbsp;/// Constructor\n\u0026nbsp;\u0026nbsp; \u0026nbsp;Timer(void);\n\n\u0026nbsp;\u0026nbsp; \u0026nbsp;/// Destructor\n\u0026nbsp;\u0026nbsp; \u0026nbsp;~Timer(void);\u003c/pre\u003e\n\n\u003cp\u003eUsers create an instance of the timer and register for the expiration. In this case, \u003ccode\u003eMyClass::MyCallback() \u003c/code\u003eis called in 1000ms.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nm_timer.Expired = MakeDelegate(\u0026amp;myClass, \u0026amp;MyClass::MyCallback, myThread);\nm_timer.Start(1000);\u003c/pre\u003e\n\n# Summary\n\n\u003cp\u003eAll delegates can be created with \u003ccode\u003eMakeDelegate()\u003c/code\u003e. The function arguments determine the delegate type returned.\u003c/p\u003e\n\n\u003cp\u003eSynchronous delegates are created using one argument for free functions and two for instance member functions.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nauto freeDelegate = MakeDelegate(\u0026amp;MyFreeFunc);\nauto memberDelegate = MakeDelegate(\u0026amp;myClass, \u0026amp;MyClass::MyMemberFunc);\u003c/pre\u003e\n\n\u003cp\u003eAdding the thread argument creates a non-blocking asynchronous delegate.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nauto freeDelegate = MakeDelegate(\u0026amp;MyFreeFunc, myThread);\nauto memberDelegate = MakeDelegate(\u0026amp;myClass, \u0026amp;MyClass::MyMemberFunc, myThread);\u003c/pre\u003e\n\n\u003cp\u003eA \u003ccode\u003estd::shared_ptr\u003c/code\u003e can replace a raw instance pointer on synchronous and non-blocking asynchronous member delegates.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nstd::shared_ptr\u0026lt;MyClass\u0026gt; myClass(new MyClass());\nauto memberDelegate = MakeDelegate(myClass, \u0026amp;MyClass::MyMemberFunc, myThread);\u003c/pre\u003e\n\n\u003cp\u003eAdding a \u003ccode\u003etimeout\u003c/code\u003e argument creates a blocking asynchronous delegate.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nauto freeDelegate = MakeDelegate(\u0026amp;MyFreeFunc, myThread, WAIT_INFINITE);\nauto memberDelegate = MakeDelegate(\u0026amp;myClass, \u0026amp;MyClass::MyMemberFunc, myThread, 5000);\u003c/pre\u003e\n\n\u003cp\u003eDelegates are added/removed from multicast containers using \u003ccode\u003eoperator+=\u003c/code\u003e and \u003ccode\u003eoperator-=\u003c/code\u003e. All containers accept all delegate types.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegate\u0026lt;void(int)\u0026gt; multicastContainer;\nmulticastContainer += MakeDelegate(\u0026amp;MyFreeFunc);\nmulticastContainer -= MakeDelegate(\u0026amp;MyFreeFunc);\u003c/pre\u003e\n\n\u003cp\u003eUse the thread-safe multicast delegate container when using asynchronous delegates to allow multiple threads to safely add/remove from the container.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nMulticastDelegateSafe\u0026lt;void(int)\u0026gt; multicastContainer;\nmulticastContainer += MakeDelegate(\u0026amp;MyFreeFunc, myThread);\nmulticastContainer -= MakeDelegate(\u0026amp;MyFreeFunc, myThread);\u003c/pre\u003e\n\n\u003cp\u003eSingle cast delegates are added and removed using \u003ccode\u003eoperator=\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nSinglecastDelegate\u0026lt;void(int)\u0026gt; singlecastContainer;\nsinglecastContainer = MakeDelegate(\u0026amp;MyFreeFunc);\nsinglecastContainer = 0;\u003c/pre\u003e\n\n\u003cp\u003eAll delegates and delegate containers are invoked using \u003ccode\u003eoperator()\u003c/code\u003e.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nif (myDelegate)\n      myDelegate(123);\u003c/pre\u003e\n\n\u003cp\u003eUse \u003ccode\u003eIsSuccess()\u003c/code\u003e on blocking delegates before using the return value or outgoing arguments.\u003c/p\u003e\n\n\u003cpre lang=\"C++\"\u003e\nif (myDelegate) \n{\n     int outInt = 0;\n     int retVal = myDelegate(\u0026amp;outInt);\n     if (myDelegate.IsSuccess()) \n     {\n          cout \u0026lt;\u0026lt; outInt \u0026lt;\u0026lt; retVal;\n     }\n}\u003c/pre\u003e\n\n# Which Callback Implementation?\n\n\u003cp\u003eI\u0026rsquo;ve documented four different asynchronous multicast callback implementations here on CodeProject. Each version has its own unique features and advantages. The sections below highlight the main differences between each solution. See the \u003cstrong\u003eReferences \u003c/strong\u003esection below for links to each article.\u003c/p\u003e\n\n## Asynchronous Multicast Callbacks in C\n\n\u003cul\u003e\n\t\u003cli\u003eImplemented in C\u003c/li\u003e\n\t\u003cli\u003eCallback function is a free or static member only\u003c/li\u003e\n\t\u003cli\u003eOne callback argument supported\u003c/li\u003e\n\t\u003cli\u003eCallback argument must be a pointer type\u003c/li\u003e\n\t\u003cli\u003eCallback argument data copied with \u003ccode\u003ememcpy\u003c/code\u003e\u003c/li\u003e\n\t\u003cli\u003eType-safety provided by macros\u003c/li\u003e\n\t\u003cli\u003eStatic array holds registered subscriber callbacks\u003c/li\u003e\n\t\u003cli\u003eNumber of registered subscribers fixed at compile time\u003c/li\u003e\n\t\u003cli\u003eFixed block memory allocator in C\u003c/li\u003e\n\t\u003cli\u003eCompact implementation\u003c/li\u003e\n\u003c/ul\u003e\n\n## Asynchronous Multicast Callbacks with Inter-Thread Messaging\n\n\u003cul\u003e\n\t\u003cli\u003eImplemented in C++\u003c/li\u003e\n\t\u003cli\u003eCallback function is a free or static member only\u003c/li\u003e\n\t\u003cli\u003eOne callback argument supported\u003c/li\u003e\n\t\u003cli\u003eCallback argument must be a pointer type\u003c/li\u003e\n\t\u003cli\u003eCallback argument data copied with copy constructor\u003c/li\u003e\n\t\u003cli\u003eType-safety provided by templates\u003c/li\u003e\n\t\u003cli\u003eMinimal use of templates\u003c/li\u003e\n\t\u003cli\u003eDynamic list of registered subscriber callbacks\u003c/li\u003e\n\t\u003cli\u003eNumber of registered subscribers expands at runtime\u003c/li\u003e\n\t\u003cli\u003eFixed block memory allocator in C++\u003c/li\u003e\n\t\u003cli\u003eCompact implementation\u003c/li\u003e\n\u003c/ul\u003e\n\n## Asynchronous Multicast Delegates in C++\n\n\u003cul\u003e\n\t\u003cli\u003eImplemented in C++\u003c/li\u003e\n\t\u003cli\u003eC++ delegate paradigm\u003c/li\u003e\n\t\u003cli\u003eAny callback function type (member, static, free)\u003c/li\u003e\n\t\u003cli\u003eMultiple callback arguments supported (up to 5)\u003c/li\u003e\n\t\u003cli\u003eCallback argument any type (value, reference, pointer, pointer to pointer)\u003c/li\u003e\n\t\u003cli\u003eCallback argument data copied with copy constructor\u003c/li\u003e\n\t\u003cli\u003eType-safety provided by templates\u003c/li\u003e\n\t\u003cli\u003eHeavy use of templates\u003c/li\u003e\n\t\u003cli\u003eDynamic list of registered subscriber callbacks\u003c/li\u003e\n\t\u003cli\u003eNumber of registered subscribers expands at runtime\u003c/li\u003e\n\t\u003cli\u003eFixed block memory allocator in C++\u003c/li\u003e\n\t\u003cli\u003eLarger implementation\u003c/li\u003e\n\u003c/ul\u003e\n\n## Asynchronous Multicast Delegates in Modern C++\n\n\u003cul\u003e\n\t\u003cli\u003eImplemented in C++ (i.e., C++17)\u003c/li\u003e\n\t\u003cli\u003eC++ delegate paradigm\u003c/li\u003e\n\t\u003cli\u003eFunction signature delegate arguments\u003c/li\u003e\n\t\u003cli\u003eAny callback function type (member, static, free)\u003c/li\u003e\n\t\u003cli\u003eMultiple callback arguments supported (N arguments supported)\u003c/li\u003e\n\t\u003cli\u003eCallback argument any type (value, reference, pointer, pointer to pointer)\u003c/li\u003e\n\t\u003cli\u003eCallback argument data copied with copy constructor\u003c/li\u003e\n\t\u003cli\u003eType-safety provided by templates\u003c/li\u003e\n\t\u003cli\u003eHeavy use of templates\u003c/li\u003e\n\t\u003cli\u003eVariadic templates\u003c/li\u003e\n\t\u003cli\u003eTemplate metaprogramming\u003c/li\u003e\n\t\u003cli\u003eDynamic list of registered subscriber callbacks\u003c/li\u003e\n\t\u003cli\u003eNumber of registered subscribers expands at runtime\u003c/li\u003e\n\t\u003cli\u003eCompact implementation (due to variadic templates)\u003c/li\u003e\n\u003c/ul\u003e\n\n# Limitations\n\n\u003cp\u003e\u003ca href=\"https://www.codeproject.com/Articles/5262271/Remote-Procedure-Calls-using-Cplusplus-Delegates\"\u003eRemote delegates\u003c/a\u003e that invoke a function located in a separate process or CPU are not currently supported by the delegate library.\u003c/p\u003e\n\n\u003cp\u003eA fixed block allocator is not currently supported. All dynamic memory is obtained from the heap using \u003ccode\u003eoperator new\u003c/code\u003e and \u003ccode\u003edelete\u003c/code\u003e.\u003c/p\u003e\n\n# References\n\n\u003cul\u003e\n\t\u003cli\u003e\u003cstrong\u003e\u003ca href=\"https://www.codeproject.com/Articles/1160934/Asynchronous-Multicast-Delegates-in-Cplusplus\"\u003eAsynchronous Multicast Delegates in C++\u003c/a\u003e\u003c/strong\u003e - by David Lafreniere\u003c/li\u003e\n\t\u003cli\u003e\u003ca href=\"https://www.codeproject.com/Articles/5262271/Remote-Procedure-Calls-using-Cplusplus-Delegates\"\u003e\u003cstrong\u003eRemote Procedure Calls using C++ Delegates\u003c/strong\u003e\u003c/a\u003e - by David Lafreniere\u003c/li\u003e\n\t\u003cli\u003e\u003ca href=\"https://www.codeproject.com/Articles/1272894/Asynchronous-Multicast-Callbacks-in-C\"\u003e\u003cstrong\u003eAsynchronous Multicast Callbacks in C\u003c/strong\u003e\u003c/a\u003e - by David Lafreniere\u003c/li\u003e\n\t\u003cli\u003e\u003ca href=\"https://www.codeproject.com/Articles/1092727/Asynchronous-Multicast-Callbacks-with-Inter-Thread\"\u003e\u003cstrong\u003eAsynchronous Multicast Callbacks with Inter-Thread Messaging\u003c/strong\u003e\u003c/a\u003e - by David Lafreniere\u003c/li\u003e\n\t\u003cli\u003e\u003ca href=\"https://www.codeproject.com/Articles/1191232/Type-Safe-Multicast-Callbacks-in-C\"\u003e\u003cstrong\u003eType-Safe Multicast Callbacks in C\u003c/strong\u003e\u003c/a\u003e - by David Lafreniere\u003c/li\u003e\n\t\u003cli\u003e\u003ca href=\"https://www.codeproject.com/Articles/1169105/Cplusplus-std-thread-Event-Loop-with-Message-Queue\"\u003e\u003cstrong\u003eC++ std::thread Event Loop with Message Queue and Timer\u003c/strong\u003e\u003c/a\u003e - by David Lafreniere\u003c/li\u003e\n\u003c/ul\u003e\n\n# Conclusion\n\n\u003cp\u003eI\u0026rsquo;ve done quite a bit of multithreaded application development over the years. Invoking a function on a destination thread with data has always been a hand-crafted, time consuming process. This library generalizes those constructs and encapsulates them into a user-friendly delegate library.\u003c/p\u003e\n\n\u003cp\u003eThe article proposes a modern C++ multicast delegate implementation supporting synchronous and asynchronous function invocation. Non-blocking asynchronous delegates offer fire-and-forget invocation whereas the blocking versions allow waiting for a return value and outgoing reference arguments from the target thread. Multicast delegate containers expand the delegate\u0026rsquo;s usefulness by allowing multiple clients to register for callback notification. Multithreaded application development is simplified by letting the library handle the low-level threading details of invoking functions and moving data across thread boundaries. The inter-thread code is neatly hidden away within the library and users only interact with an easy to use delegate API.\u003c/p\u003e\n\n\n\n\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fendurodave%2Fasyncmulticastdelegatecpp17","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fendurodave%2Fasyncmulticastdelegatecpp17","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fendurodave%2Fasyncmulticastdelegatecpp17/lists"}