Skip to content

nonstd-lite/active-lite

Repository files navigation

active lite: Active objects for C++11 and later

License Build Status

The code of active-lite is inspired on the 2010 DDJ article Prefer Using Active Objects Instead of Naked Threads by Herb Sutter, with subtitle How to automate best practices for threads and raise the semantic level of our code.

A PDF of the article is present in the doc folder.

See also Active Object pattern on Wikipedia.

Example usage

Create a counter task that counts from 0 to 10, one step per 100 ms.

// main-count.cpp

#include "nonstd/active.hpp"
#include <iostream>

/**
 * backgrounder.
 */
class counter
{
    using message = nonstd::active::helper::message;
    using base_shared_ptr = std::shared_ptr< message >;

public:
    // send the count request to the background worker class:

    void count( int const to )
    {
        helper.send( base_shared_ptr( new worker( this, to ) ) );
    }

    // the background worker class:

    class worker: public message
    {
    private:
        const int m_to;

    public:
        worker( counter * /*p*/, int to )
        : m_to( to )
        {}

        void execute() override
        {
            for ( int i = 0; i < m_to; ++i )
            {
                std::cout << "Counter: " << i << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(100));
            }
        }
    };

    // Active helper goes last, for ordered destruction.

    nonstd::active::helper helper;
};

int main()
{
    std::cout << "++main line begin" << std::endl;

    counter c; c.count( 10 );

    std::cout << "--main line end" << std::endl;
}

Compile and run

prompt> g++ -Wall -I../include main-count.cpp -o main-count.exe && main-count.exe
++main line begin
--main line end
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 6
Counter: 7
Counter: 8
Counter: 9

Synopsis

Types in namespace nonstd::active

Type Notes
class queue Thread-safe queue
class helper Helper class for Active Object pattern

About

Active objects for C++11 and later.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Contributors 2

  •  
  •