Skip to content

TutorialAdvanced

Dmitry Koplyarov edited this page Mar 9, 2016 · 15 revisions

Back to tutorial

Table of contents

Signal policies

The wigwag signals are highly customizable due to the use of policy-based design.

Signal class has four policies to configure:

You may get more detailed information at the reference page.

Using a non-default policy implementation

Often, you may find a more suitable implementation for some policy. A good example is exception handling. The default policy does not catch any exceptions, so an error in one handler may prevent other from being invoked. It's much better to catch exceptions and log them. print_to_stderr implementation fits you perfectly if you use std::exception subclasses only and the stderr logging is OK for you.

signal<void(), exception_handling::print_to_stderr> s;
token_pool tokens;

tokens += s.connect([] { throw std::runtime_error("test exception"); });

s();

Output:

std::exception in signal handler: test exception

Developing your own policy implementation

Sometimes you may want to make your own policy implementation. E.g. you would like to use your project logger for logging the exceptions.

struct log_exceptions
{
	template < typename Func_, typename... Args_ >
	void handle_exceptions(Func_&& func, Args_&&... args) const
	{
		try
		{ func(std::forward<Args_>(args)...); }
		catch (const std::exception& ex)
		{ Logger::Log(LogLevel::Error) << "Uncaught std::exception: " << ex.what(); }
	}
};

// ...

wigwag::signal<void(), log_exceptions> s;
s(); // Use the signal

Template aliases for your signal configuration

Usually, you don't really need a variety of signals in your project, so it's convenient to use template aliases for several configurations that you use.

namespace my_project
{
	template < typename Signature_>
	using signal = wigwag::signal <
			Signature_, 
			wigwag::exception_handling::print_to_stderr
		>;

	template < typename Signature_>
	using ui_signal = wigwag::signal <
			Signature_, 
			wigwag::exception_handling::print_to_stderr,
			wigwag::threading::none,
			wigwag::state_populating::none,
			wigwag::life_assurance::none
		>;
}

Now you have my_project::signal to use in the multithreaded my_project core and myproject::ui_signal that is perfectly suitable for UI due to minimal overhead:

class FileSystemListener
{
public:
	signal<void(const FilePath&)> OnFileAttributesUpdated;

	// ...
};
class Button
{
public:
	ui_signal<void()> OnClick;

	// ...
};

Signal constructors

Signal constructors have some variadic arguments, which are forwarded to the policies' internals if they have a constructor that accepts the passed type:

Single argument version:

Two arguments version:

Three arguments version:

The default signal specialization has only one policy that may accept constructor arguments: the state_populating. Thus, you have only one option from all the above: handler_processor, which effectively accepts a populator function.

However, you may use the policies that may require some parameters to be initialized (e.g. shared_mutex that needs a shared_ptr to the mutex). In this case you should use one of these signal constructors.

For example, if you want to share a single mutex between several signals, and at the same time you need populators, you should write something like this:

class MediaScanner
{
private:
	MediaScannerState              _state;
        std::vector<MediaPtr>          _media;
	std::shared_ptr<std::mutex>    _mutex;
	// ...

public:
	MediaScanner()
		: _state(MediaScannerState::Idle),
		  _mutex(std::make_shared<std::mutex>()),
		  OnStateChanged(_mutex, [&](const decltype(OnStateChanged)::handler_type& h) { h(_state); }),
		  OnMediaFound(_mutex, [&](const decltype(OnMediaFound)::handler_type& h) { for (auto&& m : _media) h(m); })
	{ }

	wigwag::signal<void(MediaScannerState), wigwag::exception_handling::default_, wigwag::threading::shared_mutex> OnStateChanged;
	wigwag::signal<void(const MediaPtr&), wigwag::exception_handling::default_, wigwag::threading::shared_mutex> OnMediaFound;

	// ...
};

Here you invoke the signal constructor with two arguments, and the signal forwards them to (lock_primitive, handler_processor) pair because both lock_primitive has a constructor that accepts the std::shared_ptrstd::mutex type, and handler_processor has a constructor that accepts the std::function<void(const HandlerType_&)> type.

Passing resource ownership and the withdrawers

class Resource;
using ResourcePtr = std::shared_ptr<Resource>;


class ResourceRequestSession
{
public:
	wigwag::signal<void(const ResourcePtr&)> OnResourceGranted;

	// ...
};


class ResourceUser
{
private:
	ResourceRequestSession _resourceRequest;
	ResourcePtr            _resource;
	wigwag::token          _token;

public:
	ResourceUser()
	{
		// Atomically connecting and obtaining the resource if it has already been granted
		_token = _resourceRequest.OnResourceGranted.connect(
			std::bind(&ResourceUser::ResourceHandler, this, std::placeholders::_1));
	}

	~ResourceUser()
	{
		// But we have a race condition here
		_token.reset();
		ResourceHandler(nullptr);
	}

private:
	void ResourceHandler(const ResourcePtr& resource)
	{
		_resource = resource;
		if (_resource)
			std::cout << "Resource granted" << std::endl;
		else
			std::cout << "Resource withdrawed" << std::endl;
	} 
};

Race here

~ResourceUser()
{
	_token.reset();
	ResourceHandler(nullptr);
}

and race there

~ResourceUser()
{
	ResourceHandler(nullptr);
	_token.reset();
}

Withdrawer

~ResourceUser()
{
	_token.reset();
}
using populator_and_withdrawer = wigwag::state_populating::populator_and_withdrawer; 

template < typename Signature_ >
using resource_signal = wigwag::signal<
		Signature_,
		wigwag::exception_handling::default_,
		wigwag::threading::default_,
		populator_and_withdrawer 
	>;

class ResourceRequestSession
{
private:
	ResourcePtr _resource;

public:
	ResourceRequestSession()
		: OnResourceGranted(populator_and_withdrawer(
			[](const std::function<void(const ResourcePtr&)>& h) { h(_resource); },
			[](const std::function<void(const ResourcePtr&)>& h) { h(nullptr); }
		))
	{ }

	resource_signal<void(const ResourcePtr&)> OnResourceGranted;

	// ...
};

Clone this wiki locally