SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Asynchronous Functions in C++
       The Generic Approach




                       Schalk W. Cronjé



                        20 April 2005

                                        ACCU 2005
                                   © Schalk W. Cronjé
Why asynchronous processing?

●   All “real-time” systems require some form of
    asynchronous architecture.

●   Anything that needs to do background
    processing whilst attending to other tasks or
    user input require an asynchronous
    architecture of some sort




                                                ACCU 2005
                                           © Schalk W. Cronjé
Cost of Switching Architecture



In any standard implementation there is usually
a significant cost of effort and time in switching
between different asynchronous mediums.




                                               ACCU 2005
                                          © Schalk W. Cronjé
McCall's Quality Factors

●   Correctness       ●   Testability
●   Reliability       ●   Flexibility
●   Usability         ●   Integrity
●   Maintainability   ●   Reusability
●   Portability       ●   Interoperability
●   Efficiency




                                             ACCU 2005
                                        © Schalk W. Cronjé
Not just Threads!


Asynchronous execution extends far beyond
just threads.

Threads are but a part of a much bigger
picture.


           Since threads are a known quantity they remain a
           good metaphor to explain the concepts surrounding
           asynchronous C++ functions
                                                   ACCU 2005
                                              © Schalk W. Cronjé
Prior Art

●   Kevlin Henney
    ACCU 2003 / 2004
    http://www.two-sdg.demon.co.uk/curbralan/papers/accu/MoreC++Threading.pdf

●   Drazen Dotlic
    C++ Users Journal, Nov 2004

●   Boost Threads

●   Boost Signals & Slots

                                                                       ACCU 2005
                                                                  © Schalk W. Cronjé
Design Goals

●   The ability to execute a free function, member
    function or functor asynchronously without
    regard to the asynchronous medium

●   The ability to change asynchronous mediums
    with as little code change as possible

●   Keep it portable



                                               ACCU 2005
                                          © Schalk W. Cronjé
The 5 Essentials

●   Launching a function asynchronously

●   Knowing whether the function has completed

●   Waiting for a function to complete

●   Collecting the result

●   Asynchronous notification


                                               ACCU 2005
                                          © Schalk W. Cronjé
Asynchronous Primitives

  ●   Threads (+mutexes etc.)
  ●   Async IO
  ●   C Signals

Of these three only threads can be ported easily and can play nicely
with C++. Therefore threads can be used to build asynchronous
mediums without being used as one itself.




                                                            ACCU 2005
                                                       © Schalk W. Cronjé
Asynchronous Mediums

●   Threads
●   Thread Pools
●   Task Queues
●   Spawned Processes
●   XML-RPC & SOAP
●   Interprocess Message Queues


                                       ACCU 2005
                                  © Schalk W. Cronjé
To detach or not

●   A detached task is one on which synchronous
    waits cannot be performed
●   Win32 & Pthreads distinguish between
    detached and non-detached threads.
●   Non-detached threads require a cleanup to be
    performed after thread has terminated
●   boost::threads uses d-tor to detach a thread
●   It is debatable whether all tasks should
    automatically be created in a detached state


                                             ACCU 2005
                                        © Schalk W. Cronjé
Building a Generic Interface




                               ACCU 2005
                          © Schalk W. Cronjé
Creating a Task
async_id create_task( Medium, Functor );
 async_id create_task( Medium, Functor );

template <typename Medium>
typename async_traits<Medium>::id_type
create_task(
   Medium const& async_medium_,
   typename async_traits<Medium>::functor_type f_
);




                                                 ACCU 2005
                                            © Schalk W. Cronjé
Asynchronous Traits #1
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
 typedef implementation-defined id_type;

 typedef implementation-defined functor_type;

 static id_type create(Medium,functor_type);


                                    id_type must be
                                    non-native, but
                                    lightweight copyable
};
 };
                                                   ACCU 2005
                                              © Schalk W. Cronjé
// Simple Medium example

class thread_id;

class SimpleThreader
{
  public:


     // Creates a thread, runs the function
     thread_id
     create( boost::function< int() > ) const;
};




                                              ACCU 2005
                                         © Schalk W. Cronjé
Asynchronous Traits #1
template <>
 template <>
struct async_traits<SimpleThreader>
 struct async_traits<SimpleThreader>
{{
 typedef SimpleThreader::thread_id id_type;

 typedef boost::function< int()> functor_type;




};
 };
                                               ACCU 2005
                                          © Schalk W. Cronjé
boost::function

 The Boost.Function library contains a family of
 class templates that are function object
 wrappers. The notion is similar to a
 generalized callback.
                       http://www.boost.org/doc/html/function.html




                                                        ACCU 2005
                                                   © Schalk W. Cronjé
// boost::function makes easy work of wrapping
// pointers to functions

int my_func( int,int );

boost::function< int(int,int) > f1 = &my_func;

std::cout << f1( 3, 4 );

// and even member functions
using std::string;
boost::function< string::size_type(string const*) >
f2= &string::size;

string s2(“Hello, World”);
std::cout << f2(&s2);


                                              ACCU 2005
                                         © Schalk W. Cronjé
Asynchronous Traits #1
template <>
 template <>
struct async_traits<SimpleThreader>
 struct async_traits<SimpleThreader>
{{
 typedef SimpleThreader::thread_id id_type;

 typedef boost::function< int()> functor_type;

 static id_type create(
   SimpleThreader const& medium_,       constness is not a
                                        requirement
   functor_type f_ )
 {return medium_.create(f_);}


};
 };
                                                ACCU 2005
                                           © Schalk W. Cronjé
// Calculate information flow of all source files
// in a directory

int calc_IF4( const char* directory_ );


SimpleThreader threader;



thread_id id= create_task(
   threader,
   boost::bind( &calc_IF4,”/myproj” )
);




                                               ACCU 2005
                                          © Schalk W. Cronjé
Completing create_task
template <typename Medium>
typename async_traits<Medium>::id_type
create_task(
  Medium const& async_medium_,
  typename async_traits<Medium>::functor_type f_
)
{


    return async_traits<Medium>::create(
       async_medium_,
       f_                             create_task can be
                                      complemented by a
    );                                version taking a mutable
}                                           reference to the
                                            asynchronous medium

                                                        ACCU 2005
                                                   © Schalk W. Cronjé
Restricting the return type
template <typename Medium>
typename async_traits<Medium>::id_type
create_task(
  Medium const& async_medium_,
  typename async_traits<Medium>::functor_type f_
)
{
    BOOST_STATIC_ASSERT((   boost::is_object<typename
       async_traits<Medium>::id_type>::value ));

    return async_traits<Medium>::create(
       async_medium_,
       f_
    );
}

                                                        ACCU 2005
                                                   © Schalk W. Cronjé
// Example thread_id

class thread_id
{
   friend class SimpleThreader;

     public:
        typedef SimpleThreader medium_type;

       thread_id();
       thread_id(thread_id const&);

       bool done() const;
       void wait() const;
       int const* data() const;

     private:
        class low_level_impl;
        boost:shared_ptr<low_level_impl> m_pImpl;

       thread_id(low_level_impl*);
};
                                                     ACCU 2005
                                                © Schalk W. Cronjé
Waiting for a Task
void wait_task( task_id );
bool task_completed( task_id );

template <typename TaskID>
void
wait_task( TaskID const& );

template <typename TaskID>
bool
task_completed( TaskID const& );




                                        ACCU 2005
                                   © Schalk W. Cronjé
Asynchronous Traits #2
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
 typedef implementation-defined id_type;
 typedef implementation-defined functor_type;
 static id_type create(Medium,functor_type);

 static void wait(id_type);

 static bool completed(id_type);

 static bool detached(id_type);


};
 };                                            ACCU 2005
                                          © Schalk W. Cronjé
Asynchronous Traits #2
template <>
 template <>
struct async_traits<SimpleThreader>
 struct async_traits<SimpleThreader>
{{
   typedef SimpleThreader::thread_id id_type;
    typedef SimpleThreader::thread_id id_type;

  static bool completed( id_type const& id_ )
  { return id_.done();}
  static void wait( id_type const& id_ )
  { id_.wait(); }

  static bool detached( id_type const& id_ );


};
 };
                                                 ACCU 2005
                                            © Schalk W. Cronjé
// Having started a task to calculate IF4
// we can check whether a task has completed


if( !task_completed( id ) )
{
  // do something else first
}

// or just simply wait for task to complete

wait_task( id );




                                              ACCU 2005
                                         © Schalk W. Cronjé
Completing wait_task
template <typename TaskID>
void
wait_task( TaskID const& task_id_ )
{
   typedef typename
      async_traits_of<TaskID>::type traits;

    if( !task_completed(task_id_) )
    {
      if( traits::detached(task_id_) )
         throw invalid_operation;
      else
         traits::wait(task_id_);
    }
}
                                               ACCU 2005
                                          © Schalk W. Cronjé
async_traits_of
template <typename TaskID>
struct async_traits_of
{
   typedef typename async_traits<
     typename TaskID::medium_type
   > type;
};




                                    Easy to specialise
                                    if necessary



                                               ACCU 2005
                                          © Schalk W. Cronjé
Collecting the Result
result_pointer task_result( task_id );


template <typename TaskID>
typename async_pointer_of<TaskID>::type
task_result( TaskID const& task_id_ );




                                     If task has not completed
                                     result is null



                                                   ACCU 2005
                                              © Schalk W. Cronjé
Asynchronous Traits #3
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
 typedef implementation-defined id_type;
 typedef implementation-defined functor_type;
 static id_type create(Medium,functor_type);
 static void wait(id_type);
 static bool completed(id_type);
 static bool detached(id_type);

 typedef implementation-defined result_type;
 typedef implementation-defined result_pointer;
 static result_pointer get_result(id_type);

};
 };
                                               ACCU 2005
                                          © Schalk W. Cronjé
Asynchronous Traits #3
template <>
 template <>
struct async_traits<SimpleThreader>
 struct async_traits<SimpleThreader>
{{
   typedef SimpleThreader::thread_id id_type;
    typedef SimpleThreader::thread_id id_type;

  typedef int result_type;
  typedef int const* result_ptr;
  static result_ptr get_result( id_type const& id_ )
  {return id_.data();}




};
 };
                                                 ACCU 2005
                                            © Schalk W. Cronjé
Completing task_result
template <typename TaskID>
typename async_pointer_of<TaskID>::type
task_result(   TaskID const& task_id_ )
{
   typedef typename
      async_traits_of<TaskID>::type traits;
    BOOST_STATIC_ASSERT(( !boost::is_void<
      typename traits::result_type>::value ));

    if( !task_completed(task_id_) )
      return async_pointer_of<TaskID>::type();
    else
      return traits::get_result(task_id_);

}
                                                ACCU 2005
                                           © Schalk W. Cronjé
Detaching & Notification

●   In order to achieve true asynchronous
    functions notifications must be implemented

●   If a function is launched in a detached mode
    the only way to know when it has finished is
    via a callback or alternative notification

●   It is important that notifications are
    asynchronous safe – at least for the medium
    on which they are applied
                                              ACCU 2005
                                         © Schalk W. Cronjé
Creating a Detached Task
async_id create_task( Medium, Functor, Notifier );
 async_id create_task( Medium, Functor, Notifier );

template <typename Medium>
typename async_traits<Medium>::id_type
create_task(
  Medium const& async_medium_,
  typename async_traits<Medium>::functor_type
f_,
   boost::function<void( typename
    async_traits<Medium>::id_type )> notify_
);



                                                ACCU 2005
                                           © Schalk W. Cronjé
Asynchronous Traits #4
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
 typedef implementation-defined id_type;
 typedef implementation-defined functor_type;
 typedef implementation-defined result_type;
 typedef implementation-defined result_pointer;
 static id_type create(Medium,functor_type);
 static void wait(id_type);
 static bool completed(id_type);
 static bool detached(id_type);
 static result_pointer get_result(id_type);
 typedef boost::function<void(id_type)>
    notification_type;
 static id_type create_detached
    (Medium,functor_type,notification_type);
};
 };                                            ACCU 2005
                                          © Schalk W. Cronjé
Asynchronous Traits #3
template <>
 template <>
struct async_traits<SimpleThreader>
 struct async_traits<SimpleThreader>
{{
   typedef SimpleThreader::thread_id id_type;
    typedef SimpleThreader::thread_id id_type;
   typedef boost::function< int()> functor_type;
    typedef boost::function< int()> functor_type;
  typedef boost::function< void(id_type) >
      notification_type;

  static id_type create_detached(
     SimpleThreader const&,
     function_type,
     notification_type
  );
};
 };
                                                  ACCU 2005
                                             © Schalk W. Cronjé
Asynchronous Traits Summary
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
 typedef implementation-defined id_type;
 typedef implementation-defined functor_type;
 typedef implementation-defined result_type;
 typedef implementation-defined result_pointer;
 typedef boost::function<void(id_type)
     notification_type;

 static id_type create(Medium,functor_type);
 static id_type create_detached
           (Medium,functor_type,notification_type);
 static void wait(id_type);
 static bool completed(id_type);
 static bool detached(id_type);
 static result_pointer get_result(id_type);
                                               ACCU 2005
};
 };
                                          © Schalk W. Cronjé
Asynchronous Function Summary

id_type create_task( Medium, Functor );
id_type create_task( Medium, Functor, Notifier );

void wait_task( id_type );

bool task_completed( id_type );

result_pointer task_result( id_type );




                                               ACCU 2005
                                          © Schalk W. Cronjé
Additional Considerations

●   Task identifiers must be lightweight copyable

●   A completed task's result must be available
    until the last task identifier for that task has
    been removed.

●   boost::shared_ptr generally the easiest way to
    accomplish both the above



                                                   ACCU 2005
                                              © Schalk W. Cronjé
Extending the Traits

●   Some mediums might not be detachable.
●   This can be handled by adding an additional
    is_detachable constant.
●   create_task(m,f,n) can assert on this during
    compile time.




                                              ACCU 2005
                                         © Schalk W. Cronjé
Extending Traits
template <typename Medium>
 template <typename Medium>
struct async_traits
 struct async_traits
{{
   BOOST_STATIC_CONSTANT(bool,is_detachable=true);
    BOOST_STATIC_CONSTANT(bool,is_detachable=true);
   // ...
    // ...
};
 };
template <typename Medium>
 template <typename Medium>
typename async_traits<Medium>::task_id
 typename async_traits<Medium>::task_id
create_task( /* parms omitted for brevity */ )
 create_task( /* parms omitted for brevity */ )
{{
     BOOST_STATIC_ASSERT(async_traits<Medium>::is_detachable);
      BOOST_STATIC_ASSERT(async_traits<Medium>::is_detachable);
}}


                                                          ACCU 2005
                                                     © Schalk W. Cronjé
Improve performance
                                         by using thread pools
                                         or task queues


Start with simple
threaded app




                    Use distributed
                    computing by going
                    out of process or
                    out of host


                                                       ACCU 2005
                                                  © Schalk W. Cronjé
Concluding




                  ACCU 2005
             © Schalk W. Cronjé
A generic approach to asynchronous execution
is not a golden solution, but it goes a long way to
 decoupling the asynchronous architecture from
               the business logic.

 It allows for selection of an architecture based
    upon underlying platform without having to
    modify the overlaying business application




                                               ACCU 2005
                                          © Schalk W. Cronjé

Más contenido relacionado

La actualidad más candente

JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017Ayush Sharma
 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: ConcurrencyPlatonov Sergey
 
Object-Based Programming Part One
Object-Based Programming Part OneObject-Based Programming Part One
Object-Based Programming Part OnePingLun Liao
 
Fun with QML
Fun with QMLFun with QML
Fun with QMLICS
 
CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013Spyros Ioakeimidis
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentICS
 
Generative Programming In The Large - Applied C++ meta-programming
Generative Programming In The Large - Applied C++ meta-programmingGenerative Programming In The Large - Applied C++ meta-programming
Generative Programming In The Large - Applied C++ meta-programmingSchalk Cronjé
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Janel Heilbrunn
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsSergio Acosta
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 

La actualidad más candente (20)

Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
UI testing in Xcode 7
UI testing in Xcode 7UI testing in Xcode 7
UI testing in Xcode 7
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017
 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: Concurrency
 
Object-Based Programming Part One
Object-Based Programming Part OneObject-Based Programming Part One
Object-Based Programming Part One
 
Fun with QML
Fun with QMLFun with QML
Fun with QML
 
JavaScript
JavaScriptJavaScript
JavaScript
 
CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013
 
SOLID
SOLIDSOLID
SOLID
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
Generative Programming In The Large - Applied C++ meta-programming
Generative Programming In The Large - Applied C++ meta-programmingGenerative Programming In The Large - Applied C++ meta-programming
Generative Programming In The Large - Applied C++ meta-programming
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2Best Practices in Qt Quick/QML - Part 2
Best Practices in Qt Quick/QML - Part 2
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 

Destacado

Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016Schalk Cronjé
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionSchalk Cronjé
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
RabbitMQ with python and ruby RuPy 2009
RabbitMQ with python and ruby RuPy 2009RabbitMQ with python and ruby RuPy 2009
RabbitMQ with python and ruby RuPy 2009Paolo Negri
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureJosé Paumard
 
Seeking Enligtenment - A journey of purpose rather than instruction
Seeking Enligtenment  - A journey of purpose rather than instructionSeeking Enligtenment  - A journey of purpose rather than instruction
Seeking Enligtenment - A journey of purpose rather than instructionSchalk Cronjé
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 

Destacado (8)

Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016Idiomatic Gradle Plugin Writing - GradleSummit 2016
Idiomatic Gradle Plugin Writing - GradleSummit 2016
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
Gradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 versionGradle in 45min - JBCN2-16 version
Gradle in 45min - JBCN2-16 version
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
RabbitMQ with python and ruby RuPy 2009
RabbitMQ with python and ruby RuPy 2009RabbitMQ with python and ruby RuPy 2009
RabbitMQ with python and ruby RuPy 2009
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
Seeking Enligtenment - A journey of purpose rather than instruction
Seeking Enligtenment  - A journey of purpose rather than instructionSeeking Enligtenment  - A journey of purpose rather than instruction
Seeking Enligtenment - A journey of purpose rather than instruction
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 

Similar a Asynchronous Functions In C++

Practical Multi-language Generative Programming
Practical Multi-language Generative ProgrammingPractical Multi-language Generative Programming
Practical Multi-language Generative ProgrammingSchalk Cronjé
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overviewFantageek
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil FrameworkVeilFramework
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...NicheTech Com. Solutions Pvt. Ltd.
 
Kernel Recipes 2015 - So you want to write a Linux driver framework
Kernel Recipes 2015 - So you want to write a Linux driver frameworkKernel Recipes 2015 - So you want to write a Linux driver framework
Kernel Recipes 2015 - So you want to write a Linux driver frameworkAnne Nicolas
 
Thread and method_2010
Thread and method_2010Thread and method_2010
Thread and method_2010敬倫 林
 
Presentation on angular 5
Presentation on angular 5Presentation on angular 5
Presentation on angular 5Ramesh Adhikari
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
An Introductory course on Verilog HDL-Verilog hdl ppr
An Introductory course on Verilog HDL-Verilog hdl pprAn Introductory course on Verilog HDL-Verilog hdl ppr
An Introductory course on Verilog HDL-Verilog hdl pprPrabhavathi P
 
MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxgopikahari7
 
Craftsmanship in Computational Work
Craftsmanship in Computational WorkCraftsmanship in Computational Work
Craftsmanship in Computational WorkYung-Yu Chen
 
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...OCCIware
 
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...Marc Dutoo
 

Similar a Asynchronous Functions In C++ (20)

Practical Multi-language Generative Programming
Practical Multi-language Generative ProgrammingPractical Multi-language Generative Programming
Practical Multi-language Generative Programming
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overview
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
 
neiljaysonching
neiljaysonchingneiljaysonching
neiljaysonching
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
Kernel Recipes 2015 - So you want to write a Linux driver framework
Kernel Recipes 2015 - So you want to write a Linux driver frameworkKernel Recipes 2015 - So you want to write a Linux driver framework
Kernel Recipes 2015 - So you want to write a Linux driver framework
 
Angular 2 in-1
Angular 2 in-1 Angular 2 in-1
Angular 2 in-1
 
Thread and method_2010
Thread and method_2010Thread and method_2010
Thread and method_2010
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Presentation on angular 5
Presentation on angular 5Presentation on angular 5
Presentation on angular 5
 
MattsonTutorialSC14.pdf
MattsonTutorialSC14.pdfMattsonTutorialSC14.pdf
MattsonTutorialSC14.pdf
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
An Introductory course on Verilog HDL-Verilog hdl ppr
An Introductory course on Verilog HDL-Verilog hdl pprAn Introductory course on Verilog HDL-Verilog hdl ppr
An Introductory course on Verilog HDL-Verilog hdl ppr
 
MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptx
 
Craftsmanship in Computational Work
Craftsmanship in Computational WorkCraftsmanship in Computational Work
Craftsmanship in Computational Work
 
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...
OCCIware Year 1 Milestone: Docker Studio, Studio Factory, pluggable XaaS runt...
 
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...
OCCIware Cloud Expo London 2016 - Docker Studio, Studio Factory, erocci bus &...
 
Lec05 buffers basic_examples
Lec05 buffers basic_examplesLec05 buffers basic_examples
Lec05 buffers basic_examples
 

Más de Schalk Cronjé

DocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM WorldDocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM WorldSchalk Cronjé
 
What's new in Asciidoctor
What's new in AsciidoctorWhat's new in Asciidoctor
What's new in AsciidoctorSchalk Cronjé
 
Probability Management
Probability ManagementProbability Management
Probability ManagementSchalk Cronjé
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionSchalk Cronjé
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You TestSchalk Cronjé
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentSchalk Cronjé
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin WritingSchalk Cronjé
 
Seeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instructionSeeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instructionSchalk Cronjé
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Beyond Estimates - Probability Management
Beyond Estimates - Probability ManagementBeyond Estimates - Probability Management
Beyond Estimates - Probability ManagementSchalk Cronjé
 
Documentation An Engineering Problem Unsolved
Documentation  An Engineering Problem UnsolvedDocumentation  An Engineering Problem Unsolved
Documentation An Engineering Problem UnsolvedSchalk Cronjé
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot WorldSchalk Cronjé
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Death of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused TestingDeath of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused TestingSchalk Cronjé
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writingSchalk Cronjé
 
Tree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & TestingTree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & TestingSchalk Cronjé
 

Más de Schalk Cronjé (20)

DocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM WorldDocuOps & Asciidoctor in a JVM World
DocuOps & Asciidoctor in a JVM World
 
DocuOps & Asciidoctor
DocuOps & AsciidoctorDocuOps & Asciidoctor
DocuOps & Asciidoctor
 
What's new in Asciidoctor
What's new in AsciidoctorWhat's new in Asciidoctor
What's new in Asciidoctor
 
Probability Management
Probability ManagementProbability Management
Probability Management
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
 
Gradle in 45min
Gradle in 45minGradle in 45min
Gradle in 45min
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin Writing
 
Seeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instructionSeeking Enligtenment - A journey of purpose rather tan instruction
Seeking Enligtenment - A journey of purpose rather tan instruction
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Beyond Estimates - Probability Management
Beyond Estimates - Probability ManagementBeyond Estimates - Probability Management
Beyond Estimates - Probability Management
 
Documentation An Engineering Problem Unsolved
Documentation  An Engineering Problem UnsolvedDocumentation  An Engineering Problem Unsolved
Documentation An Engineering Problem Unsolved
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Death of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused TestingDeath of Agile : Welcome to Value-focused Testing
Death of Agile : Welcome to Value-focused Testing
 
Asciidoctor in 15min
Asciidoctor in 15minAsciidoctor in 15min
Asciidoctor in 15min
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writing
 
Tree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & TestingTree of Knowledge - About Philosophy, Unity & Testing
Tree of Knowledge - About Philosophy, Unity & Testing
 

Asynchronous Functions In C++

  • 1. Asynchronous Functions in C++ The Generic Approach Schalk W. Cronjé 20 April 2005 ACCU 2005 © Schalk W. Cronjé
  • 2. Why asynchronous processing? ● All “real-time” systems require some form of asynchronous architecture. ● Anything that needs to do background processing whilst attending to other tasks or user input require an asynchronous architecture of some sort ACCU 2005 © Schalk W. Cronjé
  • 3. Cost of Switching Architecture In any standard implementation there is usually a significant cost of effort and time in switching between different asynchronous mediums. ACCU 2005 © Schalk W. Cronjé
  • 4. McCall's Quality Factors ● Correctness ● Testability ● Reliability ● Flexibility ● Usability ● Integrity ● Maintainability ● Reusability ● Portability ● Interoperability ● Efficiency ACCU 2005 © Schalk W. Cronjé
  • 5. Not just Threads! Asynchronous execution extends far beyond just threads. Threads are but a part of a much bigger picture. Since threads are a known quantity they remain a good metaphor to explain the concepts surrounding asynchronous C++ functions ACCU 2005 © Schalk W. Cronjé
  • 6. Prior Art ● Kevlin Henney ACCU 2003 / 2004 http://www.two-sdg.demon.co.uk/curbralan/papers/accu/MoreC++Threading.pdf ● Drazen Dotlic C++ Users Journal, Nov 2004 ● Boost Threads ● Boost Signals & Slots ACCU 2005 © Schalk W. Cronjé
  • 7. Design Goals ● The ability to execute a free function, member function or functor asynchronously without regard to the asynchronous medium ● The ability to change asynchronous mediums with as little code change as possible ● Keep it portable ACCU 2005 © Schalk W. Cronjé
  • 8. The 5 Essentials ● Launching a function asynchronously ● Knowing whether the function has completed ● Waiting for a function to complete ● Collecting the result ● Asynchronous notification ACCU 2005 © Schalk W. Cronjé
  • 9. Asynchronous Primitives ● Threads (+mutexes etc.) ● Async IO ● C Signals Of these three only threads can be ported easily and can play nicely with C++. Therefore threads can be used to build asynchronous mediums without being used as one itself. ACCU 2005 © Schalk W. Cronjé
  • 10. Asynchronous Mediums ● Threads ● Thread Pools ● Task Queues ● Spawned Processes ● XML-RPC & SOAP ● Interprocess Message Queues ACCU 2005 © Schalk W. Cronjé
  • 11. To detach or not ● A detached task is one on which synchronous waits cannot be performed ● Win32 & Pthreads distinguish between detached and non-detached threads. ● Non-detached threads require a cleanup to be performed after thread has terminated ● boost::threads uses d-tor to detach a thread ● It is debatable whether all tasks should automatically be created in a detached state ACCU 2005 © Schalk W. Cronjé
  • 12. Building a Generic Interface ACCU 2005 © Schalk W. Cronjé
  • 13. Creating a Task async_id create_task( Medium, Functor ); async_id create_task( Medium, Functor ); template <typename Medium> typename async_traits<Medium>::id_type create_task( Medium const& async_medium_, typename async_traits<Medium>::functor_type f_ ); ACCU 2005 © Schalk W. Cronjé
  • 14. Asynchronous Traits #1 template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ typedef implementation-defined id_type; typedef implementation-defined functor_type; static id_type create(Medium,functor_type); id_type must be non-native, but lightweight copyable }; }; ACCU 2005 © Schalk W. Cronjé
  • 15. // Simple Medium example class thread_id; class SimpleThreader { public: // Creates a thread, runs the function thread_id create( boost::function< int() > ) const; }; ACCU 2005 © Schalk W. Cronjé
  • 16. Asynchronous Traits #1 template <> template <> struct async_traits<SimpleThreader> struct async_traits<SimpleThreader> {{ typedef SimpleThreader::thread_id id_type; typedef boost::function< int()> functor_type; }; }; ACCU 2005 © Schalk W. Cronjé
  • 17. boost::function The Boost.Function library contains a family of class templates that are function object wrappers. The notion is similar to a generalized callback. http://www.boost.org/doc/html/function.html ACCU 2005 © Schalk W. Cronjé
  • 18. // boost::function makes easy work of wrapping // pointers to functions int my_func( int,int ); boost::function< int(int,int) > f1 = &my_func; std::cout << f1( 3, 4 ); // and even member functions using std::string; boost::function< string::size_type(string const*) > f2= &string::size; string s2(“Hello, World”); std::cout << f2(&s2); ACCU 2005 © Schalk W. Cronjé
  • 19. Asynchronous Traits #1 template <> template <> struct async_traits<SimpleThreader> struct async_traits<SimpleThreader> {{ typedef SimpleThreader::thread_id id_type; typedef boost::function< int()> functor_type; static id_type create( SimpleThreader const& medium_, constness is not a requirement functor_type f_ ) {return medium_.create(f_);} }; }; ACCU 2005 © Schalk W. Cronjé
  • 20. // Calculate information flow of all source files // in a directory int calc_IF4( const char* directory_ ); SimpleThreader threader; thread_id id= create_task( threader, boost::bind( &calc_IF4,”/myproj” ) ); ACCU 2005 © Schalk W. Cronjé
  • 21. Completing create_task template <typename Medium> typename async_traits<Medium>::id_type create_task( Medium const& async_medium_, typename async_traits<Medium>::functor_type f_ ) { return async_traits<Medium>::create( async_medium_, f_ create_task can be complemented by a ); version taking a mutable } reference to the asynchronous medium ACCU 2005 © Schalk W. Cronjé
  • 22. Restricting the return type template <typename Medium> typename async_traits<Medium>::id_type create_task( Medium const& async_medium_, typename async_traits<Medium>::functor_type f_ ) { BOOST_STATIC_ASSERT(( boost::is_object<typename async_traits<Medium>::id_type>::value )); return async_traits<Medium>::create( async_medium_, f_ ); } ACCU 2005 © Schalk W. Cronjé
  • 23. // Example thread_id class thread_id { friend class SimpleThreader; public: typedef SimpleThreader medium_type; thread_id(); thread_id(thread_id const&); bool done() const; void wait() const; int const* data() const; private: class low_level_impl; boost:shared_ptr<low_level_impl> m_pImpl; thread_id(low_level_impl*); }; ACCU 2005 © Schalk W. Cronjé
  • 24. Waiting for a Task void wait_task( task_id ); bool task_completed( task_id ); template <typename TaskID> void wait_task( TaskID const& ); template <typename TaskID> bool task_completed( TaskID const& ); ACCU 2005 © Schalk W. Cronjé
  • 25. Asynchronous Traits #2 template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ typedef implementation-defined id_type; typedef implementation-defined functor_type; static id_type create(Medium,functor_type); static void wait(id_type); static bool completed(id_type); static bool detached(id_type); }; }; ACCU 2005 © Schalk W. Cronjé
  • 26. Asynchronous Traits #2 template <> template <> struct async_traits<SimpleThreader> struct async_traits<SimpleThreader> {{ typedef SimpleThreader::thread_id id_type; typedef SimpleThreader::thread_id id_type; static bool completed( id_type const& id_ ) { return id_.done();} static void wait( id_type const& id_ ) { id_.wait(); } static bool detached( id_type const& id_ ); }; }; ACCU 2005 © Schalk W. Cronjé
  • 27. // Having started a task to calculate IF4 // we can check whether a task has completed if( !task_completed( id ) ) { // do something else first } // or just simply wait for task to complete wait_task( id ); ACCU 2005 © Schalk W. Cronjé
  • 28. Completing wait_task template <typename TaskID> void wait_task( TaskID const& task_id_ ) { typedef typename async_traits_of<TaskID>::type traits; if( !task_completed(task_id_) ) { if( traits::detached(task_id_) ) throw invalid_operation; else traits::wait(task_id_); } } ACCU 2005 © Schalk W. Cronjé
  • 29. async_traits_of template <typename TaskID> struct async_traits_of { typedef typename async_traits< typename TaskID::medium_type > type; }; Easy to specialise if necessary ACCU 2005 © Schalk W. Cronjé
  • 30. Collecting the Result result_pointer task_result( task_id ); template <typename TaskID> typename async_pointer_of<TaskID>::type task_result( TaskID const& task_id_ ); If task has not completed result is null ACCU 2005 © Schalk W. Cronjé
  • 31. Asynchronous Traits #3 template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ typedef implementation-defined id_type; typedef implementation-defined functor_type; static id_type create(Medium,functor_type); static void wait(id_type); static bool completed(id_type); static bool detached(id_type); typedef implementation-defined result_type; typedef implementation-defined result_pointer; static result_pointer get_result(id_type); }; }; ACCU 2005 © Schalk W. Cronjé
  • 32. Asynchronous Traits #3 template <> template <> struct async_traits<SimpleThreader> struct async_traits<SimpleThreader> {{ typedef SimpleThreader::thread_id id_type; typedef SimpleThreader::thread_id id_type; typedef int result_type; typedef int const* result_ptr; static result_ptr get_result( id_type const& id_ ) {return id_.data();} }; }; ACCU 2005 © Schalk W. Cronjé
  • 33. Completing task_result template <typename TaskID> typename async_pointer_of<TaskID>::type task_result( TaskID const& task_id_ ) { typedef typename async_traits_of<TaskID>::type traits; BOOST_STATIC_ASSERT(( !boost::is_void< typename traits::result_type>::value )); if( !task_completed(task_id_) ) return async_pointer_of<TaskID>::type(); else return traits::get_result(task_id_); } ACCU 2005 © Schalk W. Cronjé
  • 34. Detaching & Notification ● In order to achieve true asynchronous functions notifications must be implemented ● If a function is launched in a detached mode the only way to know when it has finished is via a callback or alternative notification ● It is important that notifications are asynchronous safe – at least for the medium on which they are applied ACCU 2005 © Schalk W. Cronjé
  • 35. Creating a Detached Task async_id create_task( Medium, Functor, Notifier ); async_id create_task( Medium, Functor, Notifier ); template <typename Medium> typename async_traits<Medium>::id_type create_task( Medium const& async_medium_, typename async_traits<Medium>::functor_type f_, boost::function<void( typename async_traits<Medium>::id_type )> notify_ ); ACCU 2005 © Schalk W. Cronjé
  • 36. Asynchronous Traits #4 template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ typedef implementation-defined id_type; typedef implementation-defined functor_type; typedef implementation-defined result_type; typedef implementation-defined result_pointer; static id_type create(Medium,functor_type); static void wait(id_type); static bool completed(id_type); static bool detached(id_type); static result_pointer get_result(id_type); typedef boost::function<void(id_type)> notification_type; static id_type create_detached (Medium,functor_type,notification_type); }; }; ACCU 2005 © Schalk W. Cronjé
  • 37. Asynchronous Traits #3 template <> template <> struct async_traits<SimpleThreader> struct async_traits<SimpleThreader> {{ typedef SimpleThreader::thread_id id_type; typedef SimpleThreader::thread_id id_type; typedef boost::function< int()> functor_type; typedef boost::function< int()> functor_type; typedef boost::function< void(id_type) > notification_type; static id_type create_detached( SimpleThreader const&, function_type, notification_type ); }; }; ACCU 2005 © Schalk W. Cronjé
  • 38. Asynchronous Traits Summary template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ typedef implementation-defined id_type; typedef implementation-defined functor_type; typedef implementation-defined result_type; typedef implementation-defined result_pointer; typedef boost::function<void(id_type) notification_type; static id_type create(Medium,functor_type); static id_type create_detached (Medium,functor_type,notification_type); static void wait(id_type); static bool completed(id_type); static bool detached(id_type); static result_pointer get_result(id_type); ACCU 2005 }; }; © Schalk W. Cronjé
  • 39. Asynchronous Function Summary id_type create_task( Medium, Functor ); id_type create_task( Medium, Functor, Notifier ); void wait_task( id_type ); bool task_completed( id_type ); result_pointer task_result( id_type ); ACCU 2005 © Schalk W. Cronjé
  • 40. Additional Considerations ● Task identifiers must be lightweight copyable ● A completed task's result must be available until the last task identifier for that task has been removed. ● boost::shared_ptr generally the easiest way to accomplish both the above ACCU 2005 © Schalk W. Cronjé
  • 41. Extending the Traits ● Some mediums might not be detachable. ● This can be handled by adding an additional is_detachable constant. ● create_task(m,f,n) can assert on this during compile time. ACCU 2005 © Schalk W. Cronjé
  • 42. Extending Traits template <typename Medium> template <typename Medium> struct async_traits struct async_traits {{ BOOST_STATIC_CONSTANT(bool,is_detachable=true); BOOST_STATIC_CONSTANT(bool,is_detachable=true); // ... // ... }; }; template <typename Medium> template <typename Medium> typename async_traits<Medium>::task_id typename async_traits<Medium>::task_id create_task( /* parms omitted for brevity */ ) create_task( /* parms omitted for brevity */ ) {{ BOOST_STATIC_ASSERT(async_traits<Medium>::is_detachable); BOOST_STATIC_ASSERT(async_traits<Medium>::is_detachable); }} ACCU 2005 © Schalk W. Cronjé
  • 43. Improve performance by using thread pools or task queues Start with simple threaded app Use distributed computing by going out of process or out of host ACCU 2005 © Schalk W. Cronjé
  • 44. Concluding ACCU 2005 © Schalk W. Cronjé
  • 45. A generic approach to asynchronous execution is not a golden solution, but it goes a long way to decoupling the asynchronous architecture from the business logic. It allows for selection of an architecture based upon underlying platform without having to modify the overlaying business application ACCU 2005 © Schalk W. Cronjé