SObjectizer 5.8
Loading...
Searching...
No Matches
so_5/mchain_fibonacci/main.cpp
/*
* Usage of select() with send_case() for calculation of Fibonacci numbers.
*/
#include <so_5/all.hpp>
#include <chrono>
using namespace std;
using namespace std::chrono_literals;
using namespace so_5;
struct quit {};
void fibonacci( mchain_t values_ch, mchain_t quit_ch )
{
int x = 0, y = 1;
do
{
r = select(
from_all().handle_n(1),
// Sends a new message of type 'int' with value 'x' inside
// when values_ch is ready for a new outgoing message.
send_case( values_ch, message_holder_t<int>::make(x),
[&x, &y] { // This block of code will be called after the send().
auto old_x = x;
x = y; y = old_x + y;
} ),
// Receive a 'quit' message from quit_ch if it is here.
receive_case( quit_ch, [](quit){} ) );
}
// Continue the loop while we send something and receive nothing.
while( r.was_sent() && !r.was_handled() );
}
int main()
{
thread fibonacci_thr;
auto thr_joiner = auto_join( fibonacci_thr );
// The chain for Fibonacci number will have limited capacity.
auto values_ch = create_mchain( sobj, 1s, 1,
mchain_props::memory_usage_t::preallocated,
mchain_props::overflow_reaction_t::abort_app );
auto quit_ch = create_mchain( sobj );
auto ch_closer = auto_close_drop_content( values_ch, quit_ch );
fibonacci_thr = thread{ fibonacci, values_ch, quit_ch };
// Read the first 10 numbers from values_ch.
receive( from( values_ch ).handle_n( 10 ),
// And show every number to the standard output.
[]( int v ) { cout << v << endl; } );
send< quit >( quit_ch );
}
A helper header file for including all public SObjectizer stuff.
A result of select from several mchains.
bool was_sent() const noexcept
bool was_handled() const noexcept
A class for holding an instance of a message.
A wrapped environment.
Private part of message limit implementation.
Definition agent.cpp:33
thread_auto_join_details::auto_joiner_t< 1+sizeof...(Tail) > auto_join(std::thread &first_thread, Tail &&... tail)
Helper function for creation of automatic joiner of std::threads.
mchain_receive_params_t< mchain_props::msg_count_status_t::undefined > from(mchain_t chain)
A helper function for simplification of creation of mchain_receive_params instance.
Definition mchain.hpp:1540
mchain_auto_close_details::auto_closer_t< sizeof...(Tail) > auto_close_drop_content(Tail &&... tail)
Helper function for automatic closing of mchains with dropping their content.
mchain_t create_mchain(environment_t &env)
Create size-unlimited chain.
mchain_props::select_case_unique_ptr_t receive_case(mchain_t chain, Handlers &&... handlers)
A helper for creation of select_case object for one multi chain select.
mchain_receive_result_t receive(const mchain_receive_params_t< Msg_Count_Status > &params, Handlers &&... handlers)
Advanced version of receive from mchain.
Definition mchain.hpp:1828