add usd-21-11-win64_py39

This commit is contained in:
Sébastien Albert committed 2021-12-07 17:43:55 +01:00
1 parent 41d23e71ba
commit ba5e1f7e67
15684 files changed
+3069957

No files matched your search

+184
View File
@@ -0,0 +1,184 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__aggregator_impl_H
#define __TBB__aggregator_impl_H
#include "../atomic.h"
#if !__TBBMALLOC_BUILD
#include "../tbb_profiling.h"
#endif
namespace tbb {
namespace interface6 {
namespace internal {
using namespace tbb::internal;
//! aggregated_operation base class
template <typename Derived>
class aggregated_operation {
public:
//! Zero value means "wait" status, all other values are "user" specified values and are defined into the scope of a class which uses "status".
uintptr_t status;
Derived *next;
aggregated_operation() : status(0), next(NULL) {}
};
//! Aggregator base class
/** An aggregator for collecting operations coming from multiple sources and executing
them serially on a single thread. operation_type must be derived from
aggregated_operation. The parameter handler_type is a functor that will be passed the
list of operations and is expected to handle each operation appropriately, setting the
status of each operation to non-zero.*/
template < typename operation_type >
class aggregator_generic {
public:
aggregator_generic() : handler_busy(false) { pending_operations = NULL; }
//! Execute an operation
/** Places an operation into the waitlist (pending_operations), and either handles the list,
or waits for the operation to complete, or returns.
The long_life_time parameter specifies the life time of the given operation object.
Operations with long_life_time == true may be accessed after execution.
A "short" life time operation (long_life_time == false) can be destroyed
during execution, and so any access to it after it was put into the waitlist,
including status check, is invalid. As a consequence, waiting for completion
of such operation causes undefined behavior.
*/
template < typename handler_type >
void execute(operation_type *op, handler_type &handle_operations, bool long_life_time = true) {
operation_type *res;
// op->status should be read before inserting the operation into the
// aggregator waitlist since it can become invalid after executing a
// handler (if the operation has 'short' life time.)
const uintptr_t status = op->status;
// ITT note: &(op->status) tag is used to cover accesses to this op node. This
// thread has created the operation, and now releases it so that the handler
// thread may handle the associated operation w/o triggering a race condition;
// thus this tag will be acquired just before the operation is handled in the
// handle_operations functor.
call_itt_notify(releasing, &(op->status));
// insert the operation in the queue.
do {
// Tools may flag the following line as a race; it is a false positive:
// This is an atomic read; we don't provide itt_hide_load_word for atomics
op->next = res = pending_operations; // NOT A RACE
} while (pending_operations.compare_and_swap(op, res) != res);
if (!res) { // first in the list; handle the operations.
// ITT note: &pending_operations tag covers access to the handler_busy flag,
// which this waiting handler thread will try to set before entering
// handle_operations.
call_itt_notify(acquired, &pending_operations);
start_handle_operations(handle_operations);
// The operation with 'short' life time can already be destroyed.
if (long_life_time)
__TBB_ASSERT(op->status, NULL);
}
// not first; wait for op to be ready.
else if (!status) { // operation is blocking here.
__TBB_ASSERT(long_life_time, "Waiting for an operation object that might be destroyed during processing.");
call_itt_notify(prepare, &(op->status));
spin_wait_while_eq(op->status, uintptr_t(0));
itt_load_word_with_acquire(op->status);
}
}
private:
//! An atomically updated list (aka mailbox) of pending operations
atomic<operation_type *> pending_operations;
//! Controls thread access to handle_operations
uintptr_t handler_busy;
//! Trigger the handling of operations when the handler is free
template < typename handler_type >
void start_handle_operations( handler_type &handle_operations ) {
operation_type *op_list;
// ITT note: &handler_busy tag covers access to pending_operations as it is passed
// between active and waiting handlers. Below, the waiting handler waits until
// the active handler releases, and the waiting handler acquires &handler_busy as
// it becomes the active_handler. The release point is at the end of this
// function, when all operations in pending_operations have been handled by the
// owner of this aggregator.
call_itt_notify(prepare, &handler_busy);
// get the handler_busy:
// only one thread can possibly spin here at a time
spin_wait_until_eq(handler_busy, uintptr_t(0));
call_itt_notify(acquired, &handler_busy);
// acquire fence not necessary here due to causality rule and surrounding atomics
__TBB_store_with_release(handler_busy, uintptr_t(1));
// ITT note: &pending_operations tag covers access to the handler_busy flag
// itself. Capturing the state of the pending_operations signifies that
// handler_busy has been set and a new active handler will now process that list's
// operations.
call_itt_notify(releasing, &pending_operations);
// grab pending_operations
op_list = pending_operations.fetch_and_store(NULL);
// handle all the operations
handle_operations(op_list);
// release the handler
itt_store_word_with_release(handler_busy, uintptr_t(0));
}
};
template < typename handler_type, typename operation_type >
class aggregator : public aggregator_generic<operation_type> {
handler_type handle_operations;
public:
aggregator() {}
explicit aggregator(handler_type h) : handle_operations(h) {}
void initialize_handler(handler_type h) { handle_operations = h; }
void execute(operation_type *op) {
aggregator_generic<operation_type>::execute(op, handle_operations);
}
};
// the most-compatible friend declaration (vs, gcc, icc) is
// template<class U, class V> friend class aggregating_functor;
template<typename aggregating_class, typename operation_list>
class aggregating_functor {
aggregating_class *fi;
public:
aggregating_functor() {}
aggregating_functor(aggregating_class *fi_) : fi(fi_) {}
void operator()(operation_list* op_list) { fi->handle_operations(op_list); }
};
} // namespace internal
} // namespace interface6
namespace internal {
using interface6::internal::aggregated_operation;
using interface6::internal::aggregator_generic;
using interface6::internal::aggregator;
using interface6::internal::aggregating_functor;
} // namespace internal
} // namespace tbb
#endif // __TBB__aggregator_impl_H
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,157 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_async_msg_impl_H
#define __TBB__flow_graph_async_msg_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
namespace internal {
template <typename T>
class async_storage {
public:
typedef receiver<T> async_storage_client;
async_storage() : my_graph(nullptr) {
my_data_ready.store<tbb::relaxed>(false);
}
~async_storage() {
// Release reference to the graph if async_storage
// was destructed before set() call
if (my_graph) {
my_graph->release_wait();
my_graph = nullptr;
}
}
template<typename C>
async_storage(C&& data) : my_graph(nullptr), my_data( std::forward<C>(data) ) {
using namespace tbb::internal;
__TBB_STATIC_ASSERT( (is_same_type<typename strip<C>::type, typename strip<T>::type>::value), "incoming type must be T" );
my_data_ready.store<tbb::relaxed>(true);
}
template<typename C>
bool set(C&& data) {
using namespace tbb::internal;
__TBB_STATIC_ASSERT( (is_same_type<typename strip<C>::type, typename strip<T>::type>::value), "incoming type must be T" );
{
tbb::spin_mutex::scoped_lock locker(my_mutex);
if (my_data_ready.load<tbb::relaxed>()) {
__TBB_ASSERT(false, "double set() call");
return false;
}
my_data = std::forward<C>(data);
my_data_ready.store<tbb::release>(true);
}
// Thread sync is on my_data_ready flag
for (typename subscriber_list_type::iterator it = my_clients.begin(); it != my_clients.end(); ++it) {
(*it)->try_put(my_data);
}
// Data was sent, release reference to the graph
if (my_graph) {
my_graph->release_wait();
my_graph = nullptr;
}
return true;
}
task* subscribe(async_storage_client& client, graph& g) {
if (! my_data_ready.load<tbb::acquire>())
{
tbb::spin_mutex::scoped_lock locker(my_mutex);
if (! my_data_ready.load<tbb::relaxed>()) {
#if TBB_USE_ASSERT
for (typename subscriber_list_type::iterator it = my_clients.begin(); it != my_clients.end(); ++it) {
__TBB_ASSERT(*it != &client, "unexpected double subscription");
}
#endif // TBB_USE_ASSERT
// Increase graph lifetime
my_graph = &g;
my_graph->reserve_wait();
// Subscribe
my_clients.push_back(&client);
return SUCCESSFULLY_ENQUEUED;
}
}
__TBB_ASSERT(my_data_ready.load<tbb::relaxed>(), "data is NOT ready");
return client.try_put_task(my_data);
}
private:
graph* my_graph;
tbb::spin_mutex my_mutex;
tbb::atomic<bool> my_data_ready;
T my_data;
typedef std::vector<async_storage_client*> subscriber_list_type;
subscriber_list_type my_clients;
};
} // namespace internal
template <typename T>
class async_msg {
template< typename > friend class receiver;
template< typename, typename > friend struct internal::async_helpers;
public:
typedef T async_msg_data_type;
async_msg() : my_storage(std::make_shared< internal::async_storage<T> >()) {}
async_msg(const T& t) : my_storage(std::make_shared< internal::async_storage<T> >(t)) {}
async_msg(T&& t) : my_storage(std::make_shared< internal::async_storage<T> >( std::move(t) )) {}
virtual ~async_msg() {}
void set(const T& t) {
my_storage->set(t);
}
void set(T&& t) {
my_storage->set( std::move(t) );
}
protected:
// Can be overridden in derived class to inform that
// async calculation chain is over
virtual void finalize() const {}
private:
typedef std::shared_ptr< internal::async_storage<T> > async_storage_ptr;
async_storage_ptr my_storage;
};
#endif // __TBB__flow_graph_async_msg_impl_H
@@ -0,0 +1,362 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_body_impl_H
#define __TBB__flow_graph_body_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
// included in namespace tbb::flow::interfaceX (in flow_graph.h)
namespace internal {
typedef tbb::internal::uint64_t tag_value;
using tbb::internal::strip;
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
template<typename ... Policies> struct Policy {};
template<typename ... Policies> struct has_policy;
template<typename ExpectedPolicy, typename FirstPolicy, typename ...Policies>
struct has_policy<ExpectedPolicy, FirstPolicy, Policies...> :
tbb::internal::bool_constant<has_policy<ExpectedPolicy, FirstPolicy>::value ||
has_policy<ExpectedPolicy, Policies...>::value> {};
template<typename ExpectedPolicy, typename SinglePolicy>
struct has_policy<ExpectedPolicy, SinglePolicy> :
tbb::internal::bool_constant<tbb::internal::is_same_type<ExpectedPolicy, SinglePolicy>::value> {};
template<typename ExpectedPolicy, typename ...Policies>
struct has_policy<ExpectedPolicy, Policy<Policies...> > : has_policy<ExpectedPolicy, Policies...> {};
#else
template<typename P1, typename P2 = void> struct Policy {};
template<typename ExpectedPolicy, typename SinglePolicy>
struct has_policy : tbb::internal::bool_constant<tbb::internal::is_same_type<ExpectedPolicy, SinglePolicy>::value> {};
template<typename ExpectedPolicy, typename P>
struct has_policy<ExpectedPolicy, Policy<P> > : has_policy<ExpectedPolicy, P> {};
template<typename ExpectedPolicy, typename P1, typename P2>
struct has_policy<ExpectedPolicy, Policy<P1, P2> > :
tbb::internal::bool_constant<has_policy<ExpectedPolicy, P1>::value || has_policy<ExpectedPolicy, P2>::value> {};
#endif
namespace graph_policy_namespace {
struct rejecting { };
struct reserving { };
struct queueing { };
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
struct lightweight { };
#endif
// K == type of field used for key-matching. Each tag-matching port will be provided
// functor that, given an object accepted by the port, will return the
/// field of type K being used for matching.
template<typename K, typename KHash=tbb_hash_compare<typename strip<K>::type > >
struct key_matching {
typedef K key_type;
typedef typename strip<K>::type base_key_type;
typedef KHash hash_compare_type;
};
// old tag_matching join's new specifier
typedef key_matching<tag_value> tag_matching;
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
// Aliases for Policy combinations
typedef interface10::internal::Policy<queueing, lightweight> queueing_lightweight;
typedef interface10::internal::Policy<rejecting, lightweight> rejecting_lightweight;
#endif
} // namespace graph_policy_namespace
// -------------- function_body containers ----------------------
//! A functor that takes no input and generates a value of type Output
template< typename Output >
class source_body : tbb::internal::no_assign {
public:
virtual ~source_body() {}
virtual bool operator()(Output &output) = 0;
virtual source_body* clone() = 0;
};
//! The leaf for source_body
template< typename Output, typename Body>
class source_body_leaf : public source_body<Output> {
public:
source_body_leaf( const Body &_body ) : body(_body) { }
bool operator()(Output &output) __TBB_override { return body( output ); }
source_body_leaf* clone() __TBB_override {
return new source_body_leaf< Output, Body >(body);
}
Body get_body() { return body; }
private:
Body body;
};
//! A functor that takes an Input and generates an Output
template< typename Input, typename Output >
class function_body : tbb::internal::no_assign {
public:
virtual ~function_body() {}
virtual Output operator()(const Input &input) = 0;
virtual function_body* clone() = 0;
};
//! the leaf for function_body
template <typename Input, typename Output, typename B>
class function_body_leaf : public function_body< Input, Output > {
public:
function_body_leaf( const B &_body ) : body(_body) { }
Output operator()(const Input &i) __TBB_override { return body(i); }
B get_body() { return body; }
function_body_leaf* clone() __TBB_override {
return new function_body_leaf< Input, Output, B >(body);
}
private:
B body;
};
//! the leaf for function_body specialized for Input and output of continue_msg
template <typename B>
class function_body_leaf< continue_msg, continue_msg, B> : public function_body< continue_msg, continue_msg > {
public:
function_body_leaf( const B &_body ) : body(_body) { }
continue_msg operator()( const continue_msg &i ) __TBB_override {
body(i);
return i;
}
B get_body() { return body; }
function_body_leaf* clone() __TBB_override {
return new function_body_leaf< continue_msg, continue_msg, B >(body);
}
private:
B body;
};
//! the leaf for function_body specialized for Output of continue_msg
template <typename Input, typename B>
class function_body_leaf< Input, continue_msg, B> : public function_body< Input, continue_msg > {
public:
function_body_leaf( const B &_body ) : body(_body) { }
continue_msg operator()(const Input &i) __TBB_override {
body(i);
return continue_msg();
}
B get_body() { return body; }
function_body_leaf* clone() __TBB_override {
return new function_body_leaf< Input, continue_msg, B >(body);
}
private:
B body;
};
//! the leaf for function_body specialized for Input of continue_msg
template <typename Output, typename B>
class function_body_leaf< continue_msg, Output, B > : public function_body< continue_msg, Output > {
public:
function_body_leaf( const B &_body ) : body(_body) { }
Output operator()(const continue_msg &i) __TBB_override {
return body(i);
}
B get_body() { return body; }
function_body_leaf* clone() __TBB_override {
return new function_body_leaf< continue_msg, Output, B >(body);
}
private:
B body;
};
//! function_body that takes an Input and a set of output ports
template<typename Input, typename OutputSet>
class multifunction_body : tbb::internal::no_assign {
public:
virtual ~multifunction_body () {}
virtual void operator()(const Input &/* input*/, OutputSet &/*oset*/) = 0;
virtual multifunction_body* clone() = 0;
virtual void* get_body_ptr() = 0;
};
//! leaf for multifunction. OutputSet can be a std::tuple or a vector.
template<typename Input, typename OutputSet, typename B >
class multifunction_body_leaf : public multifunction_body<Input, OutputSet> {
public:
multifunction_body_leaf(const B &_body) : body(_body) { }
void operator()(const Input &input, OutputSet &oset) __TBB_override {
body(input, oset); // body may explicitly put() to one or more of oset.
}
void* get_body_ptr() __TBB_override { return &body; }
multifunction_body_leaf* clone() __TBB_override {
return new multifunction_body_leaf<Input, OutputSet,B>(body);
}
private:
B body;
};
// ------ function bodies for hash_buffers and key-matching joins.
template<typename Input, typename Output>
class type_to_key_function_body : tbb::internal::no_assign {
public:
virtual ~type_to_key_function_body() {}
virtual Output operator()(const Input &input) = 0; // returns an Output
virtual type_to_key_function_body* clone() = 0;
};
// specialization for ref output
template<typename Input, typename Output>
class type_to_key_function_body<Input,Output&> : tbb::internal::no_assign {
public:
virtual ~type_to_key_function_body() {}
virtual const Output & operator()(const Input &input) = 0; // returns a const Output&
virtual type_to_key_function_body* clone() = 0;
};
template <typename Input, typename Output, typename B>
class type_to_key_function_body_leaf : public type_to_key_function_body<Input, Output> {
public:
type_to_key_function_body_leaf( const B &_body ) : body(_body) { }
Output operator()(const Input &i) __TBB_override { return body(i); }
B get_body() { return body; }
type_to_key_function_body_leaf* clone() __TBB_override {
return new type_to_key_function_body_leaf< Input, Output, B>(body);
}
private:
B body;
};
template <typename Input, typename Output, typename B>
class type_to_key_function_body_leaf<Input,Output&,B> : public type_to_key_function_body< Input, Output&> {
public:
type_to_key_function_body_leaf( const B &_body ) : body(_body) { }
const Output& operator()(const Input &i) __TBB_override {
return body(i);
}
B get_body() { return body; }
type_to_key_function_body_leaf* clone() __TBB_override {
return new type_to_key_function_body_leaf< Input, Output&, B>(body);
}
private:
B body;
};
// --------------------------- end of function_body containers ------------------------
// --------------------------- node task bodies ---------------------------------------
//! A task that calls a node's forward_task function
template< typename NodeType >
class forward_task_bypass : public task {
NodeType &my_node;
public:
forward_task_bypass( NodeType &n ) : my_node(n) {}
task *execute() __TBB_override {
task * new_task = my_node.forward_task();
if (new_task == SUCCESSFULLY_ENQUEUED) new_task = NULL;
return new_task;
}
};
//! A task that calls a node's apply_body_bypass function, passing in an input of type Input
// return the task* unless it is SUCCESSFULLY_ENQUEUED, in which case return NULL
template< typename NodeType, typename Input >
class apply_body_task_bypass : public task {
NodeType &my_node;
Input my_input;
public:
apply_body_task_bypass( NodeType &n, const Input &i ) : my_node(n), my_input(i) {}
task *execute() __TBB_override {
task * next_task = my_node.apply_body_bypass( my_input );
if(next_task == SUCCESSFULLY_ENQUEUED) next_task = NULL;
return next_task;
}
};
//! A task that calls a node's apply_body_bypass function with no input
template< typename NodeType >
class source_task_bypass : public task {
NodeType &my_node;
public:
source_task_bypass( NodeType &n ) : my_node(n) {}
task *execute() __TBB_override {
task *new_task = my_node.apply_body_bypass( );
if(new_task == SUCCESSFULLY_ENQUEUED) return NULL;
return new_task;
}
};
// ------------------------ end of node task bodies -----------------------------------
//! An empty functor that takes an Input and returns a default constructed Output
template< typename Input, typename Output >
struct empty_body {
Output operator()( const Input & ) const { return Output(); }
};
template<typename T>
class decrementer : public continue_receiver, tbb::internal::no_copy {
T *my_node;
task *execute() __TBB_override {
return my_node->decrement_counter();
}
protected:
graph& graph_reference() __TBB_override {
return my_node->my_graph;
}
public:
typedef continue_msg input_type;
typedef continue_msg output_type;
decrementer( int number_of_predecessors = 0 ) : continue_receiver( number_of_predecessors ) { }
void set_owner( T *node ) { my_node = node; }
};
} // namespace internal
#endif // __TBB__flow_graph_body_impl_H
@@ -0,0 +1,562 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_cache_impl_H
#define __TBB__flow_graph_cache_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
// included in namespace tbb::flow::interfaceX (in flow_graph.h)
namespace internal {
//! A node_cache maintains a std::queue of elements of type T. Each operation is protected by a lock.
template< typename T, typename M=spin_mutex >
class node_cache {
public:
typedef size_t size_type;
bool empty() {
typename mutex_type::scoped_lock lock( my_mutex );
return internal_empty();
}
void add( T &n ) {
typename mutex_type::scoped_lock lock( my_mutex );
internal_push(n);
}
void remove( T &n ) {
typename mutex_type::scoped_lock lock( my_mutex );
for ( size_t i = internal_size(); i != 0; --i ) {
T &s = internal_pop();
if ( &s == &n ) return; // only remove one predecessor per request
internal_push(s);
}
}
void clear() {
while( !my_q.empty()) (void)my_q.pop();
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
my_built_predecessors.clear();
#endif
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef edge_container<T> built_predecessors_type;
built_predecessors_type &built_predecessors() { return my_built_predecessors; }
typedef typename edge_container<T>::edge_list_type predecessor_list_type;
void internal_add_built_predecessor( T &n ) {
typename mutex_type::scoped_lock lock( my_mutex );
my_built_predecessors.add_edge(n);
}
void internal_delete_built_predecessor( T &n ) {
typename mutex_type::scoped_lock lock( my_mutex );
my_built_predecessors.delete_edge(n);
}
void copy_predecessors( predecessor_list_type &v) {
typename mutex_type::scoped_lock lock( my_mutex );
my_built_predecessors.copy_edges(v);
}
size_t predecessor_count() {
typename mutex_type::scoped_lock lock(my_mutex);
return (size_t)(my_built_predecessors.edge_count());
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
protected:
typedef M mutex_type;
mutex_type my_mutex;
std::queue< T * > my_q;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
built_predecessors_type my_built_predecessors;
#endif
// Assumes lock is held
inline bool internal_empty( ) {
return my_q.empty();
}
// Assumes lock is held
inline size_type internal_size( ) {
return my_q.size();
}
// Assumes lock is held
inline void internal_push( T &n ) {
my_q.push(&n);
}
// Assumes lock is held
inline T &internal_pop() {
T *v = my_q.front();
my_q.pop();
return *v;
}
};
//! A cache of predecessors that only supports try_get
template< typename T, typename M=spin_mutex >
#if __TBB_PREVIEW_ASYNC_MSG
// TODO: make predecessor_cache type T-independent when async_msg becomes regular feature
class predecessor_cache : public node_cache< untyped_sender, M > {
#else
class predecessor_cache : public node_cache< sender<T>, M > {
#endif // __TBB_PREVIEW_ASYNC_MSG
public:
typedef M mutex_type;
typedef T output_type;
#if __TBB_PREVIEW_ASYNC_MSG
typedef untyped_sender predecessor_type;
typedef untyped_receiver successor_type;
#else
typedef sender<output_type> predecessor_type;
typedef receiver<output_type> successor_type;
#endif // __TBB_PREVIEW_ASYNC_MSG
predecessor_cache( ) : my_owner( NULL ) { }
void set_owner( successor_type *owner ) { my_owner = owner; }
bool get_item( output_type &v ) {
bool msg = false;
do {
predecessor_type *src;
{
typename mutex_type::scoped_lock lock(this->my_mutex);
if ( this->internal_empty() ) {
break;
}
src = &this->internal_pop();
}
// Try to get from this sender
msg = src->try_get( v );
if (msg == false) {
// Relinquish ownership of the edge
if (my_owner)
src->register_successor( *my_owner );
} else {
// Retain ownership of the edge
this->add(*src);
}
} while ( msg == false );
return msg;
}
// If we are removing arcs (rf_clear_edges), call clear() rather than reset().
void reset() {
if (my_owner) {
for(;;) {
predecessor_type *src;
{
if (this->internal_empty()) break;
src = &this->internal_pop();
}
src->register_successor( *my_owner );
}
}
}
protected:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
using node_cache< predecessor_type, M >::my_built_predecessors;
#endif
successor_type *my_owner;
};
//! An cache of predecessors that supports requests and reservations
// TODO: make reservable_predecessor_cache type T-independent when async_msg becomes regular feature
template< typename T, typename M=spin_mutex >
class reservable_predecessor_cache : public predecessor_cache< T, M > {
public:
typedef M mutex_type;
typedef T output_type;
#if __TBB_PREVIEW_ASYNC_MSG
typedef untyped_sender predecessor_type;
typedef untyped_receiver successor_type;
#else
typedef sender<T> predecessor_type;
typedef receiver<T> successor_type;
#endif // __TBB_PREVIEW_ASYNC_MSG
reservable_predecessor_cache( ) : reserved_src(NULL) { }
bool
try_reserve( output_type &v ) {
bool msg = false;
do {
{
typename mutex_type::scoped_lock lock(this->my_mutex);
if ( reserved_src || this->internal_empty() )
return false;
reserved_src = &this->internal_pop();
}
// Try to get from this sender
msg = reserved_src->try_reserve( v );
if (msg == false) {
typename mutex_type::scoped_lock lock(this->my_mutex);
// Relinquish ownership of the edge
reserved_src->register_successor( *this->my_owner );
reserved_src = NULL;
} else {
// Retain ownership of the edge
this->add( *reserved_src );
}
} while ( msg == false );
return msg;
}
bool
try_release( ) {
reserved_src->try_release( );
reserved_src = NULL;
return true;
}
bool
try_consume( ) {
reserved_src->try_consume( );
reserved_src = NULL;
return true;
}
void reset( ) {
reserved_src = NULL;
predecessor_cache<T,M>::reset( );
}
void clear() {
reserved_src = NULL;
predecessor_cache<T,M>::clear();
}
private:
predecessor_type *reserved_src;
};
//! An abstract cache of successors
// TODO: make successor_cache type T-independent when async_msg becomes regular feature
template<typename T, typename M=spin_rw_mutex >
class successor_cache : tbb::internal::no_copy {
protected:
typedef M mutex_type;
mutex_type my_mutex;
#if __TBB_PREVIEW_ASYNC_MSG
typedef untyped_receiver successor_type;
typedef untyped_receiver *pointer_type;
typedef untyped_sender owner_type;
#else
typedef receiver<T> successor_type;
typedef receiver<T> *pointer_type;
typedef sender<T> owner_type;
#endif // __TBB_PREVIEW_ASYNC_MSG
typedef std::list< pointer_type > successors_type;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
edge_container<successor_type> my_built_successors;
#endif
successors_type my_successors;
owner_type *my_owner;
public:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef typename edge_container<successor_type>::edge_list_type successor_list_type;
edge_container<successor_type> &built_successors() { return my_built_successors; }
void internal_add_built_successor( successor_type &r) {
typename mutex_type::scoped_lock l(my_mutex, true);
my_built_successors.add_edge( r );
}
void internal_delete_built_successor( successor_type &r) {
typename mutex_type::scoped_lock l(my_mutex, true);
my_built_successors.delete_edge(r);
}
void copy_successors( successor_list_type &v) {
typename mutex_type::scoped_lock l(my_mutex, false);
my_built_successors.copy_edges(v);
}
size_t successor_count() {
typename mutex_type::scoped_lock l(my_mutex,false);
return my_built_successors.edge_count();
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
successor_cache( ) : my_owner(NULL) {}
void set_owner( owner_type *owner ) { my_owner = owner; }
virtual ~successor_cache() {}
void register_successor( successor_type &r ) {
typename mutex_type::scoped_lock l(my_mutex, true);
my_successors.push_back( &r );
}
void remove_successor( successor_type &r ) {
typename mutex_type::scoped_lock l(my_mutex, true);
for ( typename successors_type::iterator i = my_successors.begin();
i != my_successors.end(); ++i ) {
if ( *i == & r ) {
my_successors.erase(i);
break;
}
}
}
bool empty() {
typename mutex_type::scoped_lock l(my_mutex, false);
return my_successors.empty();
}
void clear() {
my_successors.clear();
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
my_built_successors.clear();
#endif
}
#if !__TBB_PREVIEW_ASYNC_MSG
virtual task * try_put_task( const T &t ) = 0;
#endif // __TBB_PREVIEW_ASYNC_MSG
}; // successor_cache<T>
//! An abstract cache of successors, specialized to continue_msg
template<>
class successor_cache< continue_msg > : tbb::internal::no_copy {
protected:
typedef spin_rw_mutex mutex_type;
mutex_type my_mutex;
#if __TBB_PREVIEW_ASYNC_MSG
typedef untyped_receiver successor_type;
typedef untyped_receiver *pointer_type;
#else
typedef receiver<continue_msg> successor_type;
typedef receiver<continue_msg> *pointer_type;
#endif // __TBB_PREVIEW_ASYNC_MSG
typedef std::list< pointer_type > successors_type;
successors_type my_successors;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
edge_container<successor_type> my_built_successors;
typedef edge_container<successor_type>::edge_list_type successor_list_type;
#endif
sender<continue_msg> *my_owner;
public:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
edge_container<successor_type> &built_successors() { return my_built_successors; }
void internal_add_built_successor( successor_type &r) {
mutex_type::scoped_lock l(my_mutex, true);
my_built_successors.add_edge( r );
}
void internal_delete_built_successor( successor_type &r) {
mutex_type::scoped_lock l(my_mutex, true);
my_built_successors.delete_edge(r);
}
void copy_successors( successor_list_type &v) {
mutex_type::scoped_lock l(my_mutex, false);
my_built_successors.copy_edges(v);
}
size_t successor_count() {
mutex_type::scoped_lock l(my_mutex,false);
return my_built_successors.edge_count();
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
successor_cache( ) : my_owner(NULL) {}
void set_owner( sender<continue_msg> *owner ) { my_owner = owner; }
virtual ~successor_cache() {}
void register_successor( successor_type &r ) {
mutex_type::scoped_lock l(my_mutex, true);
my_successors.push_back( &r );
if ( my_owner && r.is_continue_receiver() ) {
r.register_predecessor( *my_owner );
}
}
void remove_successor( successor_type &r ) {
mutex_type::scoped_lock l(my_mutex, true);
for ( successors_type::iterator i = my_successors.begin();
i != my_successors.end(); ++i ) {
if ( *i == & r ) {
// TODO: Check if we need to test for continue_receiver before
// removing from r.
if ( my_owner )
r.remove_predecessor( *my_owner );
my_successors.erase(i);
break;
}
}
}
bool empty() {
mutex_type::scoped_lock l(my_mutex, false);
return my_successors.empty();
}
void clear() {
my_successors.clear();
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
my_built_successors.clear();
#endif
}
#if !__TBB_PREVIEW_ASYNC_MSG
virtual task * try_put_task( const continue_msg &t ) = 0;
#endif // __TBB_PREVIEW_ASYNC_MSG
}; // successor_cache< continue_msg >
//! A cache of successors that are broadcast to
// TODO: make broadcast_cache type T-independent when async_msg becomes regular feature
template<typename T, typename M=spin_rw_mutex>
class broadcast_cache : public successor_cache<T, M> {
typedef M mutex_type;
typedef typename successor_cache<T,M>::successors_type successors_type;
public:
broadcast_cache( ) {}
// as above, but call try_put_task instead, and return the last task we received (if any)
#if __TBB_PREVIEW_ASYNC_MSG
template<typename X>
task * try_put_task( const X &t ) {
#else
task * try_put_task( const T &t ) __TBB_override {
#endif // __TBB_PREVIEW_ASYNC_MSG
task * last_task = NULL;
bool upgraded = true;
typename mutex_type::scoped_lock l(this->my_mutex, upgraded);
typename successors_type::iterator i = this->my_successors.begin();
while ( i != this->my_successors.end() ) {
task *new_task = (*i)->try_put_task(t);
// workaround for icc bug
graph& graph_ref = (*i)->graph_reference();
last_task = combine_tasks(graph_ref, last_task, new_task); // enqueue if necessary
if(new_task) {
++i;
}
else { // failed
if ( (*i)->register_predecessor(*this->my_owner) ) {
if (!upgraded) {
l.upgrade_to_writer();
upgraded = true;
}
i = this->my_successors.erase(i);
} else {
++i;
}
}
}
return last_task;
}
};
//! A cache of successors that are put in a round-robin fashion
// TODO: make round_robin_cache type T-independent when async_msg becomes regular feature
template<typename T, typename M=spin_rw_mutex >
class round_robin_cache : public successor_cache<T, M> {
typedef size_t size_type;
typedef M mutex_type;
typedef typename successor_cache<T,M>::successors_type successors_type;
public:
round_robin_cache( ) {}
size_type size() {
typename mutex_type::scoped_lock l(this->my_mutex, false);
return this->my_successors.size();
}
#if __TBB_PREVIEW_ASYNC_MSG
template<typename X>
task * try_put_task( const X &t ) {
#else
task *try_put_task( const T &t ) __TBB_override {
#endif // __TBB_PREVIEW_ASYNC_MSG
bool upgraded = true;
typename mutex_type::scoped_lock l(this->my_mutex, upgraded);
typename successors_type::iterator i = this->my_successors.begin();
while ( i != this->my_successors.end() ) {
task *new_task = (*i)->try_put_task(t);
if ( new_task ) {
return new_task;
} else {
if ( (*i)->register_predecessor(*this->my_owner) ) {
if (!upgraded) {
l.upgrade_to_writer();
upgraded = true;
}
i = this->my_successors.erase(i);
}
else {
++i;
}
}
}
return NULL;
}
};
} // namespace internal
#endif // __TBB__flow_graph_cache_impl_H
+414
View File
@@ -0,0 +1,414 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_flow_graph_impl_H
#define __TBB_flow_graph_impl_H
#include "../tbb_stddef.h"
#include "../task.h"
#include "../task_arena.h"
#include "../flow_graph_abstractions.h"
#include <list>
#if TBB_DEPRECATED_FLOW_ENQUEUE
#define FLOW_SPAWN(a) tbb::task::enqueue((a))
#else
#define FLOW_SPAWN(a) tbb::task::spawn((a))
#endif
namespace tbb {
namespace flow {
namespace internal {
static tbb::task * const SUCCESSFULLY_ENQUEUED = (task *)-1;
}
namespace interface10 {
using tbb::flow::internal::SUCCESSFULLY_ENQUEUED;
class graph;
class graph_node;
template <typename GraphContainerType, typename GraphNodeType>
class graph_iterator {
friend class graph;
friend class graph_node;
public:
typedef size_t size_type;
typedef GraphNodeType value_type;
typedef GraphNodeType* pointer;
typedef GraphNodeType& reference;
typedef const GraphNodeType& const_reference;
typedef std::forward_iterator_tag iterator_category;
//! Default constructor
graph_iterator() : my_graph(NULL), current_node(NULL) {}
//! Copy constructor
graph_iterator(const graph_iterator& other) :
my_graph(other.my_graph), current_node(other.current_node)
{}
//! Assignment
graph_iterator& operator=(const graph_iterator& other) {
if (this != &other) {
my_graph = other.my_graph;
current_node = other.current_node;
}
return *this;
}
//! Dereference
reference operator*() const;
//! Dereference
pointer operator->() const;
//! Equality
bool operator==(const graph_iterator& other) const {
return ((my_graph == other.my_graph) && (current_node == other.current_node));
}
//! Inequality
bool operator!=(const graph_iterator& other) const { return !(operator==(other)); }
//! Pre-increment
graph_iterator& operator++() {
internal_forward();
return *this;
}
//! Post-increment
graph_iterator operator++(int) {
graph_iterator result = *this;
operator++();
return result;
}
private:
// the graph over which we are iterating
GraphContainerType *my_graph;
// pointer into my_graph's my_nodes list
pointer current_node;
//! Private initializing constructor for begin() and end() iterators
graph_iterator(GraphContainerType *g, bool begin);
void internal_forward();
}; // class graph_iterator
// flags to modify the behavior of the graph reset(). Can be combined.
enum reset_flags {
rf_reset_protocol = 0,
rf_reset_bodies = 1 << 0, // delete the current node body, reset to a copy of the initial node body.
rf_clear_edges = 1 << 1 // delete edges
};
namespace internal {
void activate_graph(graph& g);
void deactivate_graph(graph& g);
bool is_graph_active(graph& g);
void spawn_in_graph_arena(graph& g, tbb::task& arena_task);
void add_task_to_graph_reset_list(graph& g, tbb::task *tp);
template<typename F> void execute_in_graph_arena(graph& g, F& f);
}
//! The graph class
/** This class serves as a handle to the graph */
class graph : tbb::internal::no_copy, public tbb::flow::graph_proxy {
friend class graph_node;
template< typename Body >
class run_task : public task {
public:
run_task(Body& body) : my_body(body) {}
tbb::task *execute() __TBB_override {
my_body();
return NULL;
}
private:
Body my_body;
};
template< typename Receiver, typename Body >
class run_and_put_task : public task {
public:
run_and_put_task(Receiver &r, Body& body) : my_receiver(r), my_body(body) {}
tbb::task *execute() __TBB_override {
tbb::task *res = my_receiver.try_put_task(my_body());
if (res == SUCCESSFULLY_ENQUEUED) res = NULL;
return res;
}
private:
Receiver &my_receiver;
Body my_body;
};
typedef std::list<tbb::task *> task_list_type;
class wait_functor {
tbb::task* graph_root_task;
public:
wait_functor(tbb::task* t) : graph_root_task(t) {}
void operator()() const { graph_root_task->wait_for_all(); }
};
//! A functor that spawns a task
class spawn_functor : tbb::internal::no_assign {
tbb::task& spawn_task;
public:
spawn_functor(tbb::task& t) : spawn_task(t) {}
void operator()() const {
FLOW_SPAWN(spawn_task);
}
};
void prepare_task_arena(bool reinit = false) {
if (reinit) {
__TBB_ASSERT(my_task_arena, "task arena is NULL");
my_task_arena->terminate();
my_task_arena->initialize(tbb::task_arena::attach());
}
else {
__TBB_ASSERT(my_task_arena == NULL, "task arena is not NULL");
my_task_arena = new tbb::task_arena(tbb::task_arena::attach());
}
if (!my_task_arena->is_active()) // failed to attach
my_task_arena->initialize(); // create a new, default-initialized arena
__TBB_ASSERT(my_task_arena->is_active(), "task arena is not active");
}
public:
//! Constructs a graph with isolated task_group_context
graph();
//! Constructs a graph with use_this_context as context
explicit graph(tbb::task_group_context& use_this_context);
//! Destroys the graph.
/** Calls wait_for_all, then destroys the root task and context. */
~graph();
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
void set_name(const char *name);
#endif
void increment_wait_count() {
reserve_wait();
}
void decrement_wait_count() {
release_wait();
}
//! Used to register that an external entity may still interact with the graph.
/** The graph will not return from wait_for_all until a matching number of decrement_wait_count calls
is made. */
void reserve_wait() __TBB_override;
//! Deregisters an external entity that may have interacted with the graph.
/** The graph will not return from wait_for_all until all the number of decrement_wait_count calls
matches the number of increment_wait_count calls. */
void release_wait() __TBB_override;
//! Spawns a task that runs a body and puts its output to a specific receiver
/** The task is spawned as a child of the graph. This is useful for running tasks
that need to block a wait_for_all() on the graph. For example a one-off source. */
template< typename Receiver, typename Body >
void run(Receiver &r, Body body) {
if (internal::is_graph_active(*this)) {
task* rtask = new (task::allocate_additional_child_of(*root_task()))
run_and_put_task< Receiver, Body >(r, body);
my_task_arena->execute(spawn_functor(*rtask));
}
}
//! Spawns a task that runs a function object
/** The task is spawned as a child of the graph. This is useful for running tasks
that need to block a wait_for_all() on the graph. For example a one-off source. */
template< typename Body >
void run(Body body) {
if (internal::is_graph_active(*this)) {
task* rtask = new (task::allocate_additional_child_of(*root_task())) run_task< Body >(body);
my_task_arena->execute(spawn_functor(*rtask));
}
}
//! Wait until graph is idle and decrement_wait_count calls equals increment_wait_count calls.
/** The waiting thread will go off and steal work while it is block in the wait_for_all. */
void wait_for_all() {
cancelled = false;
caught_exception = false;
if (my_root_task) {
#if TBB_USE_EXCEPTIONS
try {
#endif
my_task_arena->execute(wait_functor(my_root_task));
cancelled = my_context->is_group_execution_cancelled();
#if TBB_USE_EXCEPTIONS
}
catch (...) {
my_root_task->set_ref_count(1);
my_context->reset();
caught_exception = true;
cancelled = true;
throw;
}
#endif
// TODO: the "if" condition below is just a work-around to support the concurrent wait
// mode. The cancellation and exception mechanisms are still broken in this mode.
// Consider using task group not to re-implement the same functionality.
if (!(my_context->traits() & tbb::task_group_context::concurrent_wait)) {
my_context->reset(); // consistent with behavior in catch()
my_root_task->set_ref_count(1);
}
}
}
//! Returns the root task of the graph
tbb::task * root_task() {
return my_root_task;
}
// ITERATORS
template<typename C, typename N>
friend class graph_iterator;
// Graph iterator typedefs
typedef graph_iterator<graph, graph_node> iterator;
typedef graph_iterator<const graph, const graph_node> const_iterator;
// Graph iterator constructors
//! start iterator
iterator begin();
//! end iterator
iterator end();
//! start const iterator
const_iterator begin() const;
//! end const iterator
const_iterator end() const;
//! start const iterator
const_iterator cbegin() const;
//! end const iterator
const_iterator cend() const;
//! return status of graph execution
bool is_cancelled() { return cancelled; }
bool exception_thrown() { return caught_exception; }
// thread-unsafe state reset.
void reset(reset_flags f = rf_reset_protocol);
private:
tbb::task *my_root_task;
tbb::task_group_context *my_context;
bool own_context;
bool cancelled;
bool caught_exception;
bool my_is_active;
task_list_type my_reset_task_list;
graph_node *my_nodes, *my_nodes_last;
tbb::spin_mutex nodelist_mutex;
void register_node(graph_node *n);
void remove_node(graph_node *n);
tbb::task_arena* my_task_arena;
friend void internal::activate_graph(graph& g);
friend void internal::deactivate_graph(graph& g);
friend bool internal::is_graph_active(graph& g);
friend void internal::spawn_in_graph_arena(graph& g, tbb::task& arena_task);
friend void internal::add_task_to_graph_reset_list(graph& g, tbb::task *tp);
template<typename F> friend void internal::execute_in_graph_arena(graph& g, F& f);
friend class tbb::interface7::internal::task_arena_base;
}; // class graph
//! The base of all graph nodes.
class graph_node : tbb::internal::no_copy {
friend class graph;
template<typename C, typename N>
friend class graph_iterator;
protected:
graph& my_graph;
graph_node *next, *prev;
public:
explicit graph_node(graph& g);
virtual ~graph_node();
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
virtual void set_name(const char *name) = 0;
#endif
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
virtual void extract() = 0;
#endif
protected:
// performs the reset on an individual node.
virtual void reset_node(reset_flags f = rf_reset_protocol) = 0;
}; // class graph_node
namespace internal {
inline void activate_graph(graph& g) {
g.my_is_active = true;
}
inline void deactivate_graph(graph& g) {
g.my_is_active = false;
}
inline bool is_graph_active(graph& g) {
return g.my_is_active;
}
//! Executes custom functor inside graph arena
template<typename F>
inline void execute_in_graph_arena(graph& g, F& f) {
if (is_graph_active(g)) {
__TBB_ASSERT(g.my_task_arena && g.my_task_arena->is_active(), NULL);
g.my_task_arena->execute(f);
}
}
//! Spawns a task inside graph arena
inline void spawn_in_graph_arena(graph& g, tbb::task& arena_task) {
graph::spawn_functor s_fn(arena_task);
execute_in_graph_arena(g, s_fn);
}
inline void add_task_to_graph_reset_list(graph& g, tbb::task *tp) {
g.my_reset_task_list.push_back(tp);
}
} // namespace internal
} // namespace interface10
} // namespace flow
} // namespace tbb
#endif // __TBB_flow_graph_impl_H
@@ -0,0 +1,484 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_indexer_impl_H
#define __TBB__flow_graph_indexer_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#include "_flow_graph_types_impl.h"
namespace internal {
// Output of the indexer_node is a tbb::flow::tagged_msg, and will be of
// the form tagged_msg<tag, result>
// where the value of tag will indicate which result was put to the
// successor.
template<typename IndexerNodeBaseType, typename T, size_t K>
task* do_try_put(const T &v, void *p) {
typename IndexerNodeBaseType::output_type o(K, v);
return reinterpret_cast<IndexerNodeBaseType *>(p)->try_put_task(&o);
}
template<typename TupleTypes,int N>
struct indexer_helper {
template<typename IndexerNodeBaseType, typename PortTuple>
static inline void set_indexer_node_pointer(PortTuple &my_input, IndexerNodeBaseType *p, graph& g) {
typedef typename tuple_element<N-1, TupleTypes>::type T;
task *(*indexer_node_put_task)(const T&, void *) = do_try_put<IndexerNodeBaseType, T, N-1>;
tbb::flow::get<N-1>(my_input).set_up(p, indexer_node_put_task, g);
indexer_helper<TupleTypes,N-1>::template set_indexer_node_pointer<IndexerNodeBaseType,PortTuple>(my_input, p, g);
}
template<typename InputTuple>
static inline void reset_inputs(InputTuple &my_input, reset_flags f) {
indexer_helper<TupleTypes,N-1>::reset_inputs(my_input, f);
tbb::flow::get<N-1>(my_input).reset_receiver(f);
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
template<typename InputTuple>
static inline void extract(InputTuple &my_input) {
indexer_helper<TupleTypes,N-1>::extract(my_input);
tbb::flow::get<N-1>(my_input).extract_receiver();
}
#endif
};
template<typename TupleTypes>
struct indexer_helper<TupleTypes,1> {
template<typename IndexerNodeBaseType, typename PortTuple>
static inline void set_indexer_node_pointer(PortTuple &my_input, IndexerNodeBaseType *p, graph& g) {
typedef typename tuple_element<0, TupleTypes>::type T;
task *(*indexer_node_put_task)(const T&, void *) = do_try_put<IndexerNodeBaseType, T, 0>;
tbb::flow::get<0>(my_input).set_up(p, indexer_node_put_task, g);
}
template<typename InputTuple>
static inline void reset_inputs(InputTuple &my_input, reset_flags f) {
tbb::flow::get<0>(my_input).reset_receiver(f);
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
template<typename InputTuple>
static inline void extract(InputTuple &my_input) {
tbb::flow::get<0>(my_input).extract_receiver();
}
#endif
};
template<typename T>
class indexer_input_port : public receiver<T> {
private:
void* my_indexer_ptr;
typedef task* (* forward_function_ptr)(T const &, void* );
forward_function_ptr my_try_put_task;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
spin_mutex my_pred_mutex;
typedef typename receiver<T>::built_predecessors_type built_predecessors_type;
built_predecessors_type my_built_predecessors;
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
graph* my_graph;
public:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
indexer_input_port() : my_pred_mutex(), my_graph(NULL) {}
indexer_input_port( const indexer_input_port & other) : receiver<T>(), my_pred_mutex(), my_graph(other.my_graph) {
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
void set_up(void* p, forward_function_ptr f, graph& g) {
my_indexer_ptr = p;
my_try_put_task = f;
my_graph = &g;
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef typename receiver<T>::predecessor_list_type predecessor_list_type;
typedef typename receiver<T>::predecessor_type predecessor_type;
built_predecessors_type &built_predecessors() __TBB_override { return my_built_predecessors; }
size_t predecessor_count() __TBB_override {
spin_mutex::scoped_lock l(my_pred_mutex);
return my_built_predecessors.edge_count();
}
void internal_add_built_predecessor(predecessor_type &p) __TBB_override {
spin_mutex::scoped_lock l(my_pred_mutex);
my_built_predecessors.add_edge(p);
}
void internal_delete_built_predecessor(predecessor_type &p) __TBB_override {
spin_mutex::scoped_lock l(my_pred_mutex);
my_built_predecessors.delete_edge(p);
}
void copy_predecessors( predecessor_list_type &v) __TBB_override {
spin_mutex::scoped_lock l(my_pred_mutex);
my_built_predecessors.copy_edges(v);
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
protected:
template< typename R, typename B > friend class run_and_put_task;
template<typename X, typename Y> friend class internal::broadcast_cache;
template<typename X, typename Y> friend class internal::round_robin_cache;
task *try_put_task(const T &v) __TBB_override {
return my_try_put_task(v, my_indexer_ptr);
}
graph& graph_reference() __TBB_override {
return *my_graph;
}
public:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
void reset_receiver(reset_flags f) __TBB_override { if(f&rf_clear_edges) my_built_predecessors.clear(); }
#else
void reset_receiver(reset_flags /*f*/) __TBB_override { }
#endif
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
void extract_receiver() { my_built_predecessors.receiver_extract(*this); }
#endif
};
template<typename InputTuple, typename OutputType, typename StructTypes>
class indexer_node_FE {
public:
static const int N = tbb::flow::tuple_size<InputTuple>::value;
typedef OutputType output_type;
typedef InputTuple input_type;
// Some versions of Intel(R) C++ Compiler fail to generate an implicit constructor for the class which has std::tuple as a member.
indexer_node_FE() : my_inputs() {}
input_type &input_ports() { return my_inputs; }
protected:
input_type my_inputs;
};
//! indexer_node_base
template<typename InputTuple, typename OutputType, typename StructTypes>
class indexer_node_base : public graph_node, public indexer_node_FE<InputTuple, OutputType,StructTypes>,
public sender<OutputType> {
protected:
using graph_node::my_graph;
public:
static const size_t N = tbb::flow::tuple_size<InputTuple>::value;
typedef OutputType output_type;
typedef StructTypes tuple_types;
typedef typename sender<output_type>::successor_type successor_type;
typedef indexer_node_FE<InputTuple, output_type,StructTypes> input_ports_type;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef typename sender<output_type>::built_successors_type built_successors_type;
typedef typename sender<output_type>::successor_list_type successor_list_type;
#endif
private:
// ----------- Aggregator ------------
enum op_type { reg_succ, rem_succ, try__put_task
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
, add_blt_succ, del_blt_succ,
blt_succ_cnt, blt_succ_cpy
#endif
};
typedef indexer_node_base<InputTuple,output_type,StructTypes> class_type;
class indexer_node_base_operation : public aggregated_operation<indexer_node_base_operation> {
public:
char type;
union {
output_type const *my_arg;
successor_type *my_succ;
task *bypass_t;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
size_t cnt_val;
successor_list_type *succv;
#endif
};
indexer_node_base_operation(const output_type* e, op_type t) :
type(char(t)), my_arg(e) {}
indexer_node_base_operation(const successor_type &s, op_type t) : type(char(t)),
my_succ(const_cast<successor_type *>(&s)) {}
indexer_node_base_operation(op_type t) : type(char(t)) {}
};
typedef internal::aggregating_functor<class_type, indexer_node_base_operation> handler_type;
friend class internal::aggregating_functor<class_type, indexer_node_base_operation>;
aggregator<handler_type, indexer_node_base_operation> my_aggregator;
void handle_operations(indexer_node_base_operation* op_list) {
indexer_node_base_operation *current;
while(op_list) {
current = op_list;
op_list = op_list->next;
switch(current->type) {
case reg_succ:
my_successors.register_successor(*(current->my_succ));
__TBB_store_with_release(current->status, SUCCEEDED);
break;
case rem_succ:
my_successors.remove_successor(*(current->my_succ));
__TBB_store_with_release(current->status, SUCCEEDED);
break;
case try__put_task: {
current->bypass_t = my_successors.try_put_task(*(current->my_arg));
__TBB_store_with_release(current->status, SUCCEEDED); // return of try_put_task actual return value
}
break;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
case add_blt_succ:
my_successors.internal_add_built_successor(*(current->my_succ));
__TBB_store_with_release(current->status, SUCCEEDED);
break;
case del_blt_succ:
my_successors.internal_delete_built_successor(*(current->my_succ));
__TBB_store_with_release(current->status, SUCCEEDED);
break;
case blt_succ_cnt:
current->cnt_val = my_successors.successor_count();
__TBB_store_with_release(current->status, SUCCEEDED);
break;
case blt_succ_cpy:
my_successors.copy_successors(*(current->succv));
__TBB_store_with_release(current->status, SUCCEEDED);
break;
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
}
}
}
// ---------- end aggregator -----------
public:
indexer_node_base(graph& g) : graph_node(g), input_ports_type() {
indexer_helper<StructTypes,N>::set_indexer_node_pointer(this->my_inputs, this, g);
my_successors.set_owner(this);
my_aggregator.initialize_handler(handler_type(this));
}
indexer_node_base(const indexer_node_base& other) : graph_node(other.my_graph), input_ports_type(), sender<output_type>() {
indexer_helper<StructTypes,N>::set_indexer_node_pointer(this->my_inputs, this, other.my_graph);
my_successors.set_owner(this);
my_aggregator.initialize_handler(handler_type(this));
}
bool register_successor(successor_type &r) __TBB_override {
indexer_node_base_operation op_data(r, reg_succ);
my_aggregator.execute(&op_data);
return op_data.status == SUCCEEDED;
}
bool remove_successor( successor_type &r) __TBB_override {
indexer_node_base_operation op_data(r, rem_succ);
my_aggregator.execute(&op_data);
return op_data.status == SUCCEEDED;
}
task * try_put_task(output_type const *v) { // not a virtual method in this class
indexer_node_base_operation op_data(v, try__put_task);
my_aggregator.execute(&op_data);
return op_data.bypass_t;
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
built_successors_type &built_successors() __TBB_override { return my_successors.built_successors(); }
void internal_add_built_successor( successor_type &r) __TBB_override {
indexer_node_base_operation op_data(r, add_blt_succ);
my_aggregator.execute(&op_data);
}
void internal_delete_built_successor( successor_type &r) __TBB_override {
indexer_node_base_operation op_data(r, del_blt_succ);
my_aggregator.execute(&op_data);
}
size_t successor_count() __TBB_override {
indexer_node_base_operation op_data(blt_succ_cnt);
my_aggregator.execute(&op_data);
return op_data.cnt_val;
}
void copy_successors( successor_list_type &v) __TBB_override {
indexer_node_base_operation op_data(blt_succ_cpy);
op_data.succv = &v;
my_aggregator.execute(&op_data);
}
void extract() __TBB_override {
my_successors.built_successors().sender_extract(*this);
indexer_helper<StructTypes,N>::extract(this->my_inputs);
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
protected:
void reset_node(reset_flags f) __TBB_override {
if(f & rf_clear_edges) {
my_successors.clear();
indexer_helper<StructTypes,N>::reset_inputs(this->my_inputs,f);
}
}
private:
broadcast_cache<output_type, null_rw_mutex> my_successors;
}; //indexer_node_base
template<int N, typename InputTuple> struct input_types;
template<typename InputTuple>
struct input_types<1, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename internal::tagged_msg<size_t, first_type > type;
};
template<typename InputTuple>
struct input_types<2, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type> type;
};
template<typename InputTuple>
struct input_types<3, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type> type;
};
template<typename InputTuple>
struct input_types<4, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type> type;
};
template<typename InputTuple>
struct input_types<5, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type> type;
};
template<typename InputTuple>
struct input_types<6, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename tuple_element<5, InputTuple>::type sixth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type, sixth_type> type;
};
template<typename InputTuple>
struct input_types<7, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename tuple_element<5, InputTuple>::type sixth_type;
typedef typename tuple_element<6, InputTuple>::type seventh_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type, sixth_type,
seventh_type> type;
};
template<typename InputTuple>
struct input_types<8, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename tuple_element<5, InputTuple>::type sixth_type;
typedef typename tuple_element<6, InputTuple>::type seventh_type;
typedef typename tuple_element<7, InputTuple>::type eighth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type, sixth_type,
seventh_type, eighth_type> type;
};
template<typename InputTuple>
struct input_types<9, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename tuple_element<5, InputTuple>::type sixth_type;
typedef typename tuple_element<6, InputTuple>::type seventh_type;
typedef typename tuple_element<7, InputTuple>::type eighth_type;
typedef typename tuple_element<8, InputTuple>::type nineth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type, sixth_type,
seventh_type, eighth_type, nineth_type> type;
};
template<typename InputTuple>
struct input_types<10, InputTuple> {
typedef typename tuple_element<0, InputTuple>::type first_type;
typedef typename tuple_element<1, InputTuple>::type second_type;
typedef typename tuple_element<2, InputTuple>::type third_type;
typedef typename tuple_element<3, InputTuple>::type fourth_type;
typedef typename tuple_element<4, InputTuple>::type fifth_type;
typedef typename tuple_element<5, InputTuple>::type sixth_type;
typedef typename tuple_element<6, InputTuple>::type seventh_type;
typedef typename tuple_element<7, InputTuple>::type eighth_type;
typedef typename tuple_element<8, InputTuple>::type nineth_type;
typedef typename tuple_element<9, InputTuple>::type tenth_type;
typedef typename internal::tagged_msg<size_t, first_type, second_type, third_type,
fourth_type, fifth_type, sixth_type,
seventh_type, eighth_type, nineth_type,
tenth_type> type;
};
// type generators
template<typename OutputTuple>
struct indexer_types : public input_types<tuple_size<OutputTuple>::value, OutputTuple> {
static const int N = tbb::flow::tuple_size<OutputTuple>::value;
typedef typename input_types<N, OutputTuple>::type output_type;
typedef typename wrap_tuple_elements<N,indexer_input_port,OutputTuple>::type input_ports_type;
typedef internal::indexer_node_FE<input_ports_type,output_type,OutputTuple> indexer_FE_type;
typedef internal::indexer_node_base<input_ports_type, output_type, OutputTuple> indexer_base_type;
};
template<class OutputTuple>
class unfolded_indexer_node : public indexer_types<OutputTuple>::indexer_base_type {
public:
typedef typename indexer_types<OutputTuple>::input_ports_type input_ports_type;
typedef OutputTuple tuple_types;
typedef typename indexer_types<OutputTuple>::output_type output_type;
private:
typedef typename indexer_types<OutputTuple>::indexer_base_type base_type;
public:
unfolded_indexer_node(graph& g) : base_type(g) {}
unfolded_indexer_node(const unfolded_indexer_node &other) : base_type(other) {}
};
} /* namespace internal */
#endif /* __TBB__flow_graph_indexer_impl_H */
@@ -0,0 +1,288 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_item_buffer_impl_H
#define __TBB__flow_graph_item_buffer_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#include "tbb/internal/_flow_graph_types_impl.h" // for aligned_pair
// in namespace tbb::flow::interfaceX (included in _flow_graph_node_impl.h)
//! Expandable buffer of items. The possible operations are push, pop,
//* tests for empty and so forth. No mutual exclusion is built in.
//* objects are constructed into and explicitly-destroyed. get_my_item gives
// a read-only reference to the item in the buffer. set_my_item may be called
// with either an empty or occupied slot.
using internal::aligned_pair;
using internal::alignment_of;
namespace internal {
template <typename T, typename A=cache_aligned_allocator<T> >
class item_buffer {
public:
typedef T item_type;
enum buffer_item_state { no_item=0, has_item=1, reserved_item=2 };
protected:
typedef size_t size_type;
typedef typename aligned_pair<item_type, buffer_item_state>::type buffer_item_type;
typedef typename A::template rebind<buffer_item_type>::other allocator_type;
buffer_item_type *my_array;
size_type my_array_size;
static const size_type initial_buffer_size = 4;
size_type my_head;
size_type my_tail;
bool buffer_empty() const { return my_head == my_tail; }
buffer_item_type &item(size_type i) {
__TBB_ASSERT(!(size_type(&(my_array[i&(my_array_size-1)].second))%alignment_of<buffer_item_state>::value),NULL);
__TBB_ASSERT(!(size_type(&(my_array[i&(my_array_size-1)].first))%alignment_of<item_type>::value), NULL);
return my_array[i & (my_array_size - 1) ];
}
const buffer_item_type &item(size_type i) const {
__TBB_ASSERT(!(size_type(&(my_array[i&(my_array_size-1)].second))%alignment_of<buffer_item_state>::value), NULL);
__TBB_ASSERT(!(size_type(&(my_array[i&(my_array_size-1)].first))%alignment_of<item_type>::value), NULL);
return my_array[i & (my_array_size-1)];
}
bool my_item_valid(size_type i) const { return (i < my_tail) && (i >= my_head) && (item(i).second != no_item); }
bool my_item_reserved(size_type i) const { return item(i).second == reserved_item; }
// object management in buffer
const item_type &get_my_item(size_t i) const {
__TBB_ASSERT(my_item_valid(i),"attempt to get invalid item");
item_type *itm = (tbb::internal::punned_cast<item_type *>(&(item(i).first)));
return *(const item_type *)itm;
}
// may be called with an empty slot or a slot that has already been constructed into.
void set_my_item(size_t i, const item_type &o) {
if(item(i).second != no_item) {
destroy_item(i);
}
new(&(item(i).first)) item_type(o);
item(i).second = has_item;
}
// destructively-fetch an object from the buffer
void fetch_item(size_t i, item_type &o) {
__TBB_ASSERT(my_item_valid(i), "Trying to fetch an empty slot");
o = get_my_item(i); // could have std::move assign semantics
destroy_item(i);
}
// move an existing item from one slot to another. The moved-to slot must be unoccupied,
// the moved-from slot must exist and not be reserved. The after, from will be empty,
// to will be occupied but not reserved
void move_item(size_t to, size_t from) {
__TBB_ASSERT(!my_item_valid(to), "Trying to move to a non-empty slot");
__TBB_ASSERT(my_item_valid(from), "Trying to move from an empty slot");
set_my_item(to, get_my_item(from)); // could have std::move semantics
destroy_item(from);
}
// put an item in an empty slot. Return true if successful, else false
bool place_item(size_t here, const item_type &me) {
#if !TBB_DEPRECATED_SEQUENCER_DUPLICATES
if(my_item_valid(here)) return false;
#endif
set_my_item(here, me);
return true;
}
// could be implemented with std::move semantics
void swap_items(size_t i, size_t j) {
__TBB_ASSERT(my_item_valid(i) && my_item_valid(j), "attempt to swap invalid item(s)");
item_type temp = get_my_item(i);
set_my_item(i, get_my_item(j));
set_my_item(j, temp);
}
void destroy_item(size_type i) {
__TBB_ASSERT(my_item_valid(i), "destruction of invalid item");
(tbb::internal::punned_cast<item_type *>(&(item(i).first)))->~item_type();
item(i).second = no_item;
}
// returns the front element
const item_type& front() const
{
__TBB_ASSERT(my_item_valid(my_head), "attempt to fetch head non-item");
return get_my_item(my_head);
}
// returns the back element
const item_type& back() const
{
__TBB_ASSERT(my_item_valid(my_tail - 1), "attempt to fetch head non-item");
return get_my_item(my_tail - 1);
}
// following methods are for reservation of the front of a bufffer.
void reserve_item(size_type i) { __TBB_ASSERT(my_item_valid(i) && !my_item_reserved(i), "item cannot be reserved"); item(i).second = reserved_item; }
void release_item(size_type i) { __TBB_ASSERT(my_item_reserved(i), "item is not reserved"); item(i).second = has_item; }
void destroy_front() { destroy_item(my_head); ++my_head; }
void destroy_back() { destroy_item(my_tail-1); --my_tail; }
// we have to be able to test against a new tail value without changing my_tail
// grow_array doesn't work if we change my_tail when the old array is too small
size_type size(size_t new_tail = 0) { return (new_tail ? new_tail : my_tail) - my_head; }
size_type capacity() { return my_array_size; }
// sequencer_node does not use this method, so we don't
// need a version that passes in the new_tail value.
bool buffer_full() { return size() >= capacity(); }
//! Grows the internal array.
void grow_my_array( size_t minimum_size ) {
// test that we haven't made the structure inconsistent.
__TBB_ASSERT(capacity() >= my_tail - my_head, "total items exceed capacity");
size_type new_size = my_array_size ? 2*my_array_size : initial_buffer_size;
while( new_size<minimum_size )
new_size*=2;
buffer_item_type* new_array = allocator_type().allocate(new_size);
// initialize validity to "no"
for( size_type i=0; i<new_size; ++i ) { new_array[i].second = no_item; }
for( size_type i=my_head; i<my_tail; ++i) {
if(my_item_valid(i)) { // sequencer_node may have empty slots
// placement-new copy-construct; could be std::move
char *new_space = (char *)&(new_array[i&(new_size-1)].first);
(void)new(new_space) item_type(get_my_item(i));
new_array[i&(new_size-1)].second = item(i).second;
}
}
clean_up_buffer(/*reset_pointers*/false);
my_array = new_array;
my_array_size = new_size;
}
bool push_back(item_type &v) {
if(buffer_full()) {
grow_my_array(size() + 1);
}
set_my_item(my_tail, v);
++my_tail;
return true;
}
bool pop_back(item_type &v) {
if (!my_item_valid(my_tail-1)) {
return false;
}
v = this->back();
destroy_back();
return true;
}
bool pop_front(item_type &v) {
if(!my_item_valid(my_head)) {
return false;
}
v = this->front();
destroy_front();
return true;
}
// This is used both for reset and for grow_my_array. In the case of grow_my_array
// we want to retain the values of the head and tail.
void clean_up_buffer(bool reset_pointers) {
if (my_array) {
for( size_type i=my_head; i<my_tail; ++i ) {
if(my_item_valid(i))
destroy_item(i);
}
allocator_type().deallocate(my_array,my_array_size);
}
my_array = NULL;
if(reset_pointers) {
my_head = my_tail = my_array_size = 0;
}
}
public:
//! Constructor
item_buffer( ) : my_array(NULL), my_array_size(0),
my_head(0), my_tail(0) {
grow_my_array(initial_buffer_size);
}
~item_buffer() {
clean_up_buffer(/*reset_pointers*/true);
}
void reset() { clean_up_buffer(/*reset_pointers*/true); grow_my_array(initial_buffer_size); }
};
//! item_buffer with reservable front-end. NOTE: if reserving, do not
//* complete operation with pop_front(); use consume_front().
//* No synchronization built-in.
template<typename T, typename A=cache_aligned_allocator<T> >
class reservable_item_buffer : public item_buffer<T, A> {
protected:
using item_buffer<T, A>::my_item_valid;
using item_buffer<T, A>::my_head;
public:
reservable_item_buffer() : item_buffer<T, A>(), my_reserved(false) {}
void reset() {my_reserved = false; item_buffer<T,A>::reset(); }
protected:
bool reserve_front(T &v) {
if(my_reserved || !my_item_valid(this->my_head)) return false;
my_reserved = true;
// reserving the head
v = this->front();
this->reserve_item(this->my_head);
return true;
}
void consume_front() {
__TBB_ASSERT(my_reserved, "Attempt to consume a non-reserved item");
this->destroy_front();
my_reserved = false;
}
void release_front() {
__TBB_ASSERT(my_reserved, "Attempt to release a non-reserved item");
this->release_item(this->my_head);
my_reserved = false;
}
bool my_reserved;
};
} // namespace internal
#endif // __TBB__flow_graph_item_buffer_impl_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,899 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_node_impl_H
#define __TBB__flow_graph_node_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#include "_flow_graph_item_buffer_impl.h"
//! @cond INTERNAL
namespace internal {
using tbb::internal::aggregated_operation;
using tbb::internal::aggregating_functor;
using tbb::internal::aggregator;
template< typename T, typename A >
class function_input_queue : public item_buffer<T,A> {
public:
bool empty() const {
return this->buffer_empty();
}
const T& front() const {
return this->item_buffer<T, A>::front();
}
bool pop( T& t ) {
return this->pop_front( t );
}
void pop() {
this->destroy_front();
}
bool push( T& t ) {
return this->push_back( t );
}
};
//! Input and scheduling for a function node that takes a type Input as input
// The only up-ref is apply_body_impl, which should implement the function
// call and any handling of the result.
template< typename Input, typename Policy, typename A, typename ImplType >
class function_input_base : public receiver<Input>, tbb::internal::no_assign {
enum op_type {reg_pred, rem_pred, try_fwd, tryput_bypass, app_body_bypass, occupy_concurrency
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
, add_blt_pred, del_blt_pred,
blt_pred_cnt, blt_pred_cpy // create vector copies of preds and succs
#endif
};
typedef function_input_base<Input, Policy, A, ImplType> class_type;
public:
//! The input type of this receiver
typedef Input input_type;
typedef typename receiver<input_type>::predecessor_type predecessor_type;
typedef predecessor_cache<input_type, null_mutex > predecessor_cache_type;
typedef function_input_queue<input_type, A> input_queue_type;
typedef typename A::template rebind< input_queue_type >::other queue_allocator_type;
__TBB_STATIC_ASSERT(!((internal::has_policy<queueing, Policy>::value) && (internal::has_policy<rejecting, Policy>::value)),
"queueing and rejecting policies can't be specified simultaneously");
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef typename predecessor_cache_type::built_predecessors_type built_predecessors_type;
typedef typename receiver<input_type>::predecessor_list_type predecessor_list_type;
#endif
//! Constructor for function_input_base
function_input_base( graph &g, size_t max_concurrency)
: my_graph_ref(g), my_max_concurrency(max_concurrency), my_concurrency(0),
my_queue(!internal::has_policy<rejecting, Policy>::value ? new input_queue_type() : NULL),
forwarder_busy(false)
{
my_predecessors.set_owner(this);
my_aggregator.initialize_handler(handler_type(this));
}
//! Copy constructor
function_input_base( const function_input_base& src) :
receiver<Input>(), tbb::internal::no_assign(),
my_graph_ref(src.my_graph_ref), my_max_concurrency(src.my_max_concurrency),
my_concurrency(0), my_queue(src.my_queue ? new input_queue_type() : NULL),
forwarder_busy(false)
{
my_predecessors.set_owner(this);
my_aggregator.initialize_handler(handler_type(this));
}
//! Destructor
// The queue is allocated by the constructor for {multi}function_node.
// TODO: pass the graph_buffer_policy to the base so it can allocate the queue instead.
// This would be an interface-breaking change.
virtual ~function_input_base() {
if ( my_queue ) delete my_queue;
}
task* try_put_task( const input_type& t) __TBB_override {
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
return try_put_task_impl(t, internal::has_policy<lightweight, Policy>());
#else
return try_put_task_impl(t);
#endif
}
//! Adds src to the list of cached predecessors.
bool register_predecessor( predecessor_type &src ) __TBB_override {
operation_type op_data(reg_pred);
op_data.r = &src;
my_aggregator.execute(&op_data);
return true;
}
//! Removes src from the list of cached predecessors.
bool remove_predecessor( predecessor_type &src ) __TBB_override {
operation_type op_data(rem_pred);
op_data.r = &src;
my_aggregator.execute(&op_data);
return true;
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
//! Adds to list of predecessors added by make_edge
void internal_add_built_predecessor( predecessor_type &src) __TBB_override {
operation_type op_data(add_blt_pred);
op_data.r = &src;
my_aggregator.execute(&op_data);
}
//! removes from to list of predecessors (used by remove_edge)
void internal_delete_built_predecessor( predecessor_type &src) __TBB_override {
operation_type op_data(del_blt_pred);
op_data.r = &src;
my_aggregator.execute(&op_data);
}
size_t predecessor_count() __TBB_override {
operation_type op_data(blt_pred_cnt);
my_aggregator.execute(&op_data);
return op_data.cnt_val;
}
void copy_predecessors(predecessor_list_type &v) __TBB_override {
operation_type op_data(blt_pred_cpy);
op_data.predv = &v;
my_aggregator.execute(&op_data);
}
built_predecessors_type &built_predecessors() __TBB_override {
return my_predecessors.built_predecessors();
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
protected:
void reset_function_input_base( reset_flags f) {
my_concurrency = 0;
if(my_queue) {
my_queue->reset();
}
reset_receiver(f);
forwarder_busy = false;
}
graph& my_graph_ref;
const size_t my_max_concurrency;
size_t my_concurrency;
input_queue_type *my_queue;
predecessor_cache<input_type, null_mutex > my_predecessors;
void reset_receiver( reset_flags f) __TBB_override {
if( f & rf_clear_edges) my_predecessors.clear();
else
my_predecessors.reset();
__TBB_ASSERT(!(f & rf_clear_edges) || my_predecessors.empty(), "function_input_base reset failed");
}
graph& graph_reference() __TBB_override {
return my_graph_ref;
}
task* try_get_postponed_task(const input_type& i) {
operation_type op_data(i, app_body_bypass); // tries to pop an item or get_item
my_aggregator.execute(&op_data);
return op_data.bypass_t;
}
private:
friend class apply_body_task_bypass< class_type, input_type >;
friend class forward_task_bypass< class_type >;
class operation_type : public aggregated_operation< operation_type > {
public:
char type;
union {
input_type *elem;
predecessor_type *r;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
size_t cnt_val;
predecessor_list_type *predv;
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
};
tbb::task *bypass_t;
operation_type(const input_type& e, op_type t) :
type(char(t)), elem(const_cast<input_type*>(&e)) {}
operation_type(op_type t) : type(char(t)), r(NULL) {}
};
bool forwarder_busy;
typedef internal::aggregating_functor<class_type, operation_type> handler_type;
friend class internal::aggregating_functor<class_type, operation_type>;
aggregator< handler_type, operation_type > my_aggregator;
task* perform_queued_requests() {
task* new_task = NULL;
if(my_queue) {
if(!my_queue->empty()) {
++my_concurrency;
new_task = create_body_task(my_queue->front());
my_queue->pop();
}
}
else {
input_type i;
if(my_predecessors.get_item(i)) {
++my_concurrency;
new_task = create_body_task(i);
}
}
return new_task;
}
void handle_operations(operation_type *op_list) {
operation_type *tmp;
while (op_list) {
tmp = op_list;
op_list = op_list->next;
switch (tmp->type) {
case reg_pred:
my_predecessors.add(*(tmp->r));
__TBB_store_with_release(tmp->status, SUCCEEDED);
if (!forwarder_busy) {
forwarder_busy = true;
spawn_forward_task();
}
break;
case rem_pred:
my_predecessors.remove(*(tmp->r));
__TBB_store_with_release(tmp->status, SUCCEEDED);
break;
case app_body_bypass: {
tmp->bypass_t = NULL;
__TBB_ASSERT(my_max_concurrency != 0, NULL);
--my_concurrency;
if(my_concurrency<my_max_concurrency)
tmp->bypass_t = perform_queued_requests();
__TBB_store_with_release(tmp->status, SUCCEEDED);
}
break;
case tryput_bypass: internal_try_put_task(tmp); break;
case try_fwd: internal_forward(tmp); break;
case occupy_concurrency:
if (my_concurrency < my_max_concurrency) {
++my_concurrency;
__TBB_store_with_release(tmp->status, SUCCEEDED);
} else {
__TBB_store_with_release(tmp->status, FAILED);
}
break;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
case add_blt_pred: {
my_predecessors.internal_add_built_predecessor(*(tmp->r));
__TBB_store_with_release(tmp->status, SUCCEEDED);
}
break;
case del_blt_pred:
my_predecessors.internal_delete_built_predecessor(*(tmp->r));
__TBB_store_with_release(tmp->status, SUCCEEDED);
break;
case blt_pred_cnt:
tmp->cnt_val = my_predecessors.predecessor_count();
__TBB_store_with_release(tmp->status, SUCCEEDED);
break;
case blt_pred_cpy:
my_predecessors.copy_predecessors( *(tmp->predv) );
__TBB_store_with_release(tmp->status, SUCCEEDED);
break;
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
}
}
}
//! Put to the node, but return the task instead of enqueueing it
void internal_try_put_task(operation_type *op) {
__TBB_ASSERT(my_max_concurrency != 0, NULL);
if (my_concurrency < my_max_concurrency) {
++my_concurrency;
task * new_task = create_body_task(*(op->elem));
op->bypass_t = new_task;
__TBB_store_with_release(op->status, SUCCEEDED);
} else if ( my_queue && my_queue->push(*(op->elem)) ) {
op->bypass_t = SUCCESSFULLY_ENQUEUED;
__TBB_store_with_release(op->status, SUCCEEDED);
} else {
op->bypass_t = NULL;
__TBB_store_with_release(op->status, FAILED);
}
}
//! Tries to spawn bodies if available and if concurrency allows
void internal_forward(operation_type *op) {
op->bypass_t = NULL;
if (my_concurrency < my_max_concurrency || !my_max_concurrency)
op->bypass_t = perform_queued_requests();
if(op->bypass_t)
__TBB_store_with_release(op->status, SUCCEEDED);
else {
forwarder_busy = false;
__TBB_store_with_release(op->status, FAILED);
}
}
task* internal_try_put_bypass( const input_type& t ) {
operation_type op_data(t, tryput_bypass);
my_aggregator.execute(&op_data);
if( op_data.status == internal::SUCCEEDED ) {
return op_data.bypass_t;
}
return NULL;
}
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
task* try_put_task_impl( const input_type& t, tbb::internal::true_type ) {
if( my_max_concurrency == 0 ) {
return apply_body_bypass(t);
} else {
operation_type check_op(t, occupy_concurrency);
my_aggregator.execute(&check_op);
if( check_op.status == internal::SUCCEEDED ) {
return apply_body_bypass(t);
}
return internal_try_put_bypass(t);
}
}
task* try_put_task_impl( const input_type& t, tbb::internal::false_type ) {
#else
task* try_put_task_impl( const input_type& t ) {
#endif
if( my_max_concurrency == 0 ) {
return create_body_task(t);
} else {
return internal_try_put_bypass(t);
}
}
//! Applies the body to the provided input
// then decides if more work is available
task * apply_body_bypass( const input_type &i ) {
return static_cast<ImplType *>(this)->apply_body_impl_bypass(i);
}
//! allocates a task to apply a body
inline task * create_body_task( const input_type &input ) {
return (internal::is_graph_active(my_graph_ref)) ?
new(task::allocate_additional_child_of(*(my_graph_ref.root_task())))
apply_body_task_bypass < class_type, input_type >(*this, input) :
NULL;
}
//! This is executed by an enqueued task, the "forwarder"
task *forward_task() {
operation_type op_data(try_fwd);
task *rval = NULL;
do {
op_data.status = WAIT;
my_aggregator.execute(&op_data);
if(op_data.status == SUCCEEDED) {
// workaround for icc bug
tbb::task *ttask = op_data.bypass_t;
rval = combine_tasks(my_graph_ref, rval, ttask);
}
} while (op_data.status == SUCCEEDED);
return rval;
}
inline task *create_forward_task() {
return (internal::is_graph_active(my_graph_ref)) ?
new(task::allocate_additional_child_of(*(my_graph_ref.root_task()))) forward_task_bypass< class_type >(*this) :
NULL;
}
//! Spawns a task that calls forward()
inline void spawn_forward_task() {
task* tp = create_forward_task();
if(tp) {
internal::spawn_in_graph_arena(graph_reference(), *tp);
}
}
}; // function_input_base
//! Implements methods for a function node that takes a type Input as input and sends
// a type Output to its successors.
template< typename Input, typename Output, typename Policy, typename A>
class function_input : public function_input_base<Input, Policy, A, function_input<Input,Output,Policy,A> > {
public:
typedef Input input_type;
typedef Output output_type;
typedef function_body<input_type, output_type> function_body_type;
typedef function_input<Input, Output, Policy,A> my_class;
typedef function_input_base<Input, Policy, A, my_class> base_type;
typedef function_input_queue<input_type, A> input_queue_type;
// constructor
template<typename Body>
function_input( graph &g, size_t max_concurrency, Body& body ) :
base_type(g, max_concurrency),
my_body( new internal::function_body_leaf< input_type, output_type, Body>(body) ),
my_init_body( new internal::function_body_leaf< input_type, output_type, Body>(body) ) {
}
//! Copy constructor
function_input( const function_input& src ) :
base_type(src),
my_body( src.my_init_body->clone() ),
my_init_body(src.my_init_body->clone() ) {
}
~function_input() {
delete my_body;
delete my_init_body;
}
template< typename Body >
Body copy_function_object() {
function_body_type &body_ref = *this->my_body;
return dynamic_cast< internal::function_body_leaf<input_type, output_type, Body> & >(body_ref).get_body();
}
output_type apply_body_impl( const input_type& i) {
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
// There is an extra copied needed to capture the
// body execution without the try_put
tbb::internal::fgt_begin_body( my_body );
output_type v = (*my_body)(i);
tbb::internal::fgt_end_body( my_body );
return v;
#else
return (*my_body)(i);
#endif
}
//TODO: consider moving into the base class
task * apply_body_impl_bypass( const input_type &i) {
output_type v = apply_body_impl(i);
task* postponed_task = NULL;
#if !__TBB_PREVIEW_LIGHTWEIGHT_POLICY
task* successor_task = successors().try_put_task(v);
#endif
if(base_type::my_max_concurrency != 0) {
postponed_task = base_type::try_get_postponed_task(i);
}
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
// postponed_task is either NULL or the pointer to TBB task
if(postponed_task) {
// spawn task to make it available for other workers
// since we do not know successors' execution policy
internal::spawn_in_graph_arena(base_type::graph_reference(), *postponed_task);
}
task* successor_task = successors().try_put_task(v);
if( internal::has_policy<lightweight, Policy>::value && !successor_task ) {
// Return confirmative status since current
// node's body has been executed anyway
successor_task = SUCCESSFULLY_ENQUEUED;
}
return successor_task;
#else
graph& g = base_type::my_graph_ref;
return combine_tasks(g, successor_task, postponed_task);
#endif
}
protected:
void reset_function_input(reset_flags f) {
base_type::reset_function_input_base(f);
if(f & rf_reset_bodies) {
function_body_type *tmp = my_init_body->clone();
delete my_body;
my_body = tmp;
}
}
function_body_type *my_body;
function_body_type *my_init_body;
virtual broadcast_cache<output_type > &successors() = 0;
}; // function_input
// helper templates to clear the successor edges of the output ports of an multifunction_node
template<int N> struct clear_element {
template<typename P> static void clear_this(P &p) {
(void)tbb::flow::get<N-1>(p).successors().clear();
clear_element<N-1>::clear_this(p);
}
template<typename P> static bool this_empty(P &p) {
if(tbb::flow::get<N-1>(p).successors().empty())
return clear_element<N-1>::this_empty(p);
return false;
}
};
template<> struct clear_element<1> {
template<typename P> static void clear_this(P &p) {
(void)tbb::flow::get<0>(p).successors().clear();
}
template<typename P> static bool this_empty(P &p) {
return tbb::flow::get<0>(p).successors().empty();
}
};
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
// helper templates to extract the output ports of an multifunction_node from graph
template<int N> struct extract_element {
template<typename P> static void extract_this(P &p) {
(void)tbb::flow::get<N-1>(p).successors().built_successors().sender_extract(tbb::flow::get<N-1>(p));
extract_element<N-1>::extract_this(p);
}
};
template<> struct extract_element<1> {
template<typename P> static void extract_this(P &p) {
(void)tbb::flow::get<0>(p).successors().built_successors().sender_extract(tbb::flow::get<0>(p));
}
};
#endif
//! Implements methods for a function node that takes a type Input as input
// and has a tuple of output ports specified.
template< typename Input, typename OutputPortSet, typename Policy, typename A>
class multifunction_input : public function_input_base<Input, Policy, A, multifunction_input<Input,OutputPortSet,Policy,A> > {
public:
static const int N = tbb::flow::tuple_size<OutputPortSet>::value;
typedef Input input_type;
typedef OutputPortSet output_ports_type;
typedef multifunction_body<input_type, output_ports_type> multifunction_body_type;
typedef multifunction_input<Input, OutputPortSet, Policy, A> my_class;
typedef function_input_base<Input, Policy, A, my_class> base_type;
typedef function_input_queue<input_type, A> input_queue_type;
// constructor
template<typename Body>
multifunction_input(
graph &g,
size_t max_concurrency,
Body& body) :
base_type(g, max_concurrency),
my_body( new internal::multifunction_body_leaf<input_type, output_ports_type, Body>(body) ),
my_init_body( new internal::multifunction_body_leaf<input_type, output_ports_type, Body>(body) ) {
}
//! Copy constructor
multifunction_input( const multifunction_input& src ) :
base_type(src),
my_body( src.my_init_body->clone() ),
my_init_body(src.my_init_body->clone() ) {
}
~multifunction_input() {
delete my_body;
delete my_init_body;
}
template< typename Body >
Body copy_function_object() {
multifunction_body_type &body_ref = *this->my_body;
return *static_cast<Body*>(dynamic_cast< internal::multifunction_body_leaf<input_type, output_ports_type, Body> & >(body_ref).get_body_ptr());
}
// for multifunction nodes we do not have a single successor as such. So we just tell
// the task we were successful.
//TODO: consider moving common parts with implementation in function_input into separate function
task * apply_body_impl_bypass( const input_type &i) {
tbb::internal::fgt_begin_body( my_body );
(*my_body)(i, my_output_ports);
tbb::internal::fgt_end_body( my_body );
task* ttask = NULL;
if(base_type::my_max_concurrency != 0) {
ttask = base_type::try_get_postponed_task(i);
}
return ttask ? ttask : SUCCESSFULLY_ENQUEUED;
}
output_ports_type &output_ports(){ return my_output_ports; }
protected:
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
void extract() {
extract_element<N>::extract_this(my_output_ports);
}
#endif
void reset(reset_flags f) {
base_type::reset_function_input_base(f);
if(f & rf_clear_edges)clear_element<N>::clear_this(my_output_ports);
if(f & rf_reset_bodies) {
multifunction_body_type *tmp = my_init_body->clone();
delete my_body;
my_body = tmp;
}
__TBB_ASSERT(!(f & rf_clear_edges) || clear_element<N>::this_empty(my_output_ports), "multifunction_node reset failed");
}
multifunction_body_type *my_body;
multifunction_body_type *my_init_body;
output_ports_type my_output_ports;
}; // multifunction_input
// template to refer to an output port of a multifunction_node
template<size_t N, typename MOP>
typename tbb::flow::tuple_element<N, typename MOP::output_ports_type>::type &output_port(MOP &op) {
return tbb::flow::get<N>(op.output_ports());
}
inline void check_task_and_spawn(graph& g, task* t) {
if (t && t != SUCCESSFULLY_ENQUEUED) {
internal::spawn_in_graph_arena(g, *t);
}
}
// helper structs for split_node
template<int N>
struct emit_element {
template<typename T, typename P>
static task* emit_this(graph& g, const T &t, P &p) {
// TODO: consider to collect all the tasks in task_list and spawn them all at once
task* last_task = tbb::flow::get<N-1>(p).try_put_task(tbb::flow::get<N-1>(t));
check_task_and_spawn(g, last_task);
return emit_element<N-1>::emit_this(g,t,p);
}
};
template<>
struct emit_element<1> {
template<typename T, typename P>
static task* emit_this(graph& g, const T &t, P &p) {
task* last_task = tbb::flow::get<0>(p).try_put_task(tbb::flow::get<0>(t));
check_task_and_spawn(g, last_task);
return SUCCESSFULLY_ENQUEUED;
}
};
//! Implements methods for an executable node that takes continue_msg as input
template< typename Output
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
, typename Policy
#endif
>
class continue_input : public continue_receiver {
public:
//! The input type of this receiver
typedef continue_msg input_type;
//! The output type of this receiver
typedef Output output_type;
typedef function_body<input_type, output_type> function_body_type;
typedef continue_input<output_type
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
, Policy
#endif
> class_type;
template< typename Body >
continue_input( graph &g, Body& body )
: my_graph_ref(g),
my_body( new internal::function_body_leaf< input_type, output_type, Body>(body) ),
my_init_body( new internal::function_body_leaf< input_type, output_type, Body>(body) ) { }
template< typename Body >
continue_input( graph &g, int number_of_predecessors, Body& body )
: continue_receiver( number_of_predecessors ), my_graph_ref(g),
my_body( new internal::function_body_leaf< input_type, output_type, Body>(body) ),
my_init_body( new internal::function_body_leaf< input_type, output_type, Body>(body) )
{ }
continue_input( const continue_input& src ) : continue_receiver(src),
my_graph_ref(src.my_graph_ref),
my_body( src.my_init_body->clone() ),
my_init_body( src.my_init_body->clone() ) {}
~continue_input() {
delete my_body;
delete my_init_body;
}
template< typename Body >
Body copy_function_object() {
function_body_type &body_ref = *my_body;
return dynamic_cast< internal::function_body_leaf<input_type, output_type, Body> & >(body_ref).get_body();
}
void reset_receiver( reset_flags f) __TBB_override {
continue_receiver::reset_receiver(f);
if(f & rf_reset_bodies) {
function_body_type *tmp = my_init_body->clone();
delete my_body;
my_body = tmp;
}
}
protected:
graph& my_graph_ref;
function_body_type *my_body;
function_body_type *my_init_body;
virtual broadcast_cache<output_type > &successors() = 0;
friend class apply_body_task_bypass< class_type, continue_msg >;
//! Applies the body to the provided input
task *apply_body_bypass( input_type ) {
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
// There is an extra copied needed to capture the
// body execution without the try_put
tbb::internal::fgt_begin_body( my_body );
output_type v = (*my_body)( continue_msg() );
tbb::internal::fgt_end_body( my_body );
return successors().try_put_task( v );
#else
return successors().try_put_task( (*my_body)( continue_msg() ) );
#endif
}
task* execute() __TBB_override {
if(!internal::is_graph_active(my_graph_ref)) {
return NULL;
}
#if __TBB_PREVIEW_LIGHTWEIGHT_POLICY
if(internal::has_policy<lightweight, Policy>::value) {
return apply_body_bypass( continue_msg() );
}
else
#endif
return new ( task::allocate_additional_child_of( *(my_graph_ref.root_task()) ) )
apply_body_task_bypass< class_type, continue_msg >( *this, continue_msg() );
}
graph& graph_reference() __TBB_override {
return my_graph_ref;
}
}; // continue_input
//! Implements methods for both executable and function nodes that puts Output to its successors
template< typename Output >
class function_output : public sender<Output> {
public:
template<int N> friend struct clear_element;
typedef Output output_type;
typedef typename sender<output_type>::successor_type successor_type;
typedef broadcast_cache<output_type> broadcast_cache_type;
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
typedef typename sender<output_type>::built_successors_type built_successors_type;
typedef typename sender<output_type>::successor_list_type successor_list_type;
#endif
function_output() { my_successors.set_owner(this); }
function_output(const function_output & /*other*/) : sender<output_type>() {
my_successors.set_owner(this);
}
//! Adds a new successor to this node
bool register_successor( successor_type &r ) __TBB_override {
successors().register_successor( r );
return true;
}
//! Removes a successor from this node
bool remove_successor( successor_type &r ) __TBB_override {
successors().remove_successor( r );
return true;
}
#if TBB_PREVIEW_FLOW_GRAPH_FEATURES
built_successors_type &built_successors() __TBB_override { return successors().built_successors(); }
void internal_add_built_successor( successor_type &r) __TBB_override {
successors().internal_add_built_successor( r );
}
void internal_delete_built_successor( successor_type &r) __TBB_override {
successors().internal_delete_built_successor( r );
}
size_t successor_count() __TBB_override {
return successors().successor_count();
}
void copy_successors( successor_list_type &v) __TBB_override {
successors().copy_successors(v);
}
#endif /* TBB_PREVIEW_FLOW_GRAPH_FEATURES */
// for multifunction_node. The function_body that implements
// the node will have an input and an output tuple of ports. To put
// an item to a successor, the body should
//
// get<I>(output_ports).try_put(output_value);
//
// if task pointer is returned will always spawn and return true, else
// return value will be bool returned from successors.try_put.
task *try_put_task(const output_type &i) { // not a virtual method in this class
return my_successors.try_put_task(i);
}
broadcast_cache_type &successors() { return my_successors; }
protected:
broadcast_cache_type my_successors;
}; // function_output
template< typename Output >
class multifunction_output : public function_output<Output> {
public:
typedef Output output_type;
typedef function_output<output_type> base_type;
using base_type::my_successors;
multifunction_output() : base_type() {my_successors.set_owner(this);}
multifunction_output( const multifunction_output &/*other*/) : base_type() { my_successors.set_owner(this); }
bool try_put(const output_type &i) {
task *res = try_put_task(i);
if(!res) return false;
if(res != SUCCESSFULLY_ENQUEUED) {
FLOW_SPAWN(*res); // TODO: Spawn task inside arena
}
return true;
}
protected:
task* try_put_task(const output_type &i) {
return my_successors.try_put_task(i);
}
template <int N> friend struct emit_element;
}; // multifunction_output
//composite_node
#if TBB_PREVIEW_FLOW_GRAPH_TRACE && __TBB_FLOW_GRAPH_CPP11_FEATURES
template<typename CompositeType>
void add_nodes_impl(CompositeType*, bool) {}
template< typename CompositeType, typename NodeType1, typename... NodeTypes >
void add_nodes_impl(CompositeType *c_node, bool visible, const NodeType1& n1, const NodeTypes&... n) {
void *addr = const_cast<NodeType1 *>(&n1);
if(visible)
tbb::internal::itt_relation_add( tbb::internal::ITT_DOMAIN_FLOW, c_node, tbb::internal::FLOW_NODE, tbb::internal::__itt_relation_is_parent_of, addr, tbb::internal::FLOW_NODE );
else
tbb::internal::itt_relation_add( tbb::internal::ITT_DOMAIN_FLOW, addr, tbb::internal::FLOW_NODE, tbb::internal::__itt_relation_is_child_of, c_node, tbb::internal::FLOW_NODE );
add_nodes_impl(c_node, visible, n...);
}
#endif
} // internal
#endif // __TBB__flow_graph_node_impl_H
@@ -0,0 +1,745 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_flow_graph_streaming_H
#define __TBB_flow_graph_streaming_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#if __TBB_PREVIEW_STREAMING_NODE
// Included in namespace tbb::flow::interfaceX (in flow_graph.h)
namespace internal {
template <int N1, int N2>
struct port_ref_impl {
// "+1" since the port_ref range is a closed interval (includes its endpoints).
static const int size = N2 - N1 + 1;
};
} // internal
// The purpose of the port_ref_impl is the pretty syntax: the deduction of a compile-time constant is processed from the return type.
// So it is possible to use this helper without parentheses, e.g. "port_ref<0>".
template <int N1, int N2 = N1>
internal::port_ref_impl<N1,N2> port_ref() {
return internal::port_ref_impl<N1,N2>();
};
namespace internal {
template <typename T>
struct num_arguments {
static const int value = 1;
};
template <int N1, int N2>
struct num_arguments<port_ref_impl<N1,N2>(*)()> {
static const int value = port_ref_impl<N1,N2>::size;
};
template <int N1, int N2>
struct num_arguments<port_ref_impl<N1,N2>> {
static const int value = port_ref_impl<N1,N2>::size;
};
template <typename... Args>
void ignore_return_values( Args&&... ) {}
template <typename T>
T or_return_values( T&& t ) { return t; }
template <typename T, typename... Rest>
T or_return_values( T&& t, Rest&&... rest ) {
return t | or_return_values( std::forward<Rest>(rest)... );
}
template<typename JP>
struct key_from_policy {
typedef size_t type;
typedef std::false_type is_key_matching;
};
template<typename Key>
struct key_from_policy< key_matching<Key> > {
typedef Key type;
typedef std::true_type is_key_matching;
};
template<typename Key>
struct key_from_policy< key_matching<Key&> > {
typedef const Key &type;
typedef std::true_type is_key_matching;
};
template<typename Device, typename Key>
class streaming_device_with_key {
Device my_device;
typename std::decay<Key>::type my_key;
public:
// TODO: investigate why default constructor is required
streaming_device_with_key() {}
streaming_device_with_key( const Device& d, Key k ) : my_device( d ), my_key( k ) {}
Key key() const { return my_key; }
const Device& device() const { return my_device; }
};
// --------- Kernel argument helpers --------- //
template <typename T>
struct is_port_ref_impl {
typedef std::false_type type;
};
template <int N1, int N2>
struct is_port_ref_impl< port_ref_impl<N1, N2> > {
typedef std::true_type type;
};
template <int N1, int N2>
struct is_port_ref_impl< port_ref_impl<N1, N2>( * )() > {
typedef std::true_type type;
};
template <typename T>
struct is_port_ref {
typedef typename is_port_ref_impl< typename tbb::internal::strip<T>::type >::type type;
};
template <typename ...Args1>
struct convert_and_call_impl;
template <typename A1, typename ...Args1>
struct convert_and_call_impl<A1, Args1...> {
static const size_t my_delta = 1; // Index 0 contains device
template <typename F, typename Tuple, typename ...Args2>
static void doit(F& f, Tuple& t, A1& a1, Args1&... args1, Args2&... args2) {
convert_and_call_impl<A1, Args1...>::doit_impl(typename is_port_ref<A1>::type(), f, t, a1, args1..., args2...);
}
template <typename F, typename Tuple, typename ...Args2>
static void doit_impl(std::false_type, F& f, Tuple& t, A1& a1, Args1&... args1, Args2&... args2) {
convert_and_call_impl<Args1...>::doit(f, t, args1..., args2..., a1);
}
template <typename F, typename Tuple, int N1, int N2, typename ...Args2>
static void doit_impl(std::true_type x, F& f, Tuple& t, port_ref_impl<N1, N2>, Args1&... args1, Args2&... args2) {
convert_and_call_impl<port_ref_impl<N1 + 1,N2>, Args1...>::doit_impl(x, f, t, port_ref<N1 + 1, N2>(), args1...,
args2..., std::get<N1 + my_delta>(t));
}
template <typename F, typename Tuple, int N, typename ...Args2>
static void doit_impl(std::true_type, F& f, Tuple& t, port_ref_impl<N, N>, Args1&... args1, Args2&... args2) {
convert_and_call_impl<Args1...>::doit(f, t, args1..., args2..., std::get<N + my_delta>(t));
}
template <typename F, typename Tuple, int N1, int N2, typename ...Args2>
static void doit_impl(std::true_type x, F& f, Tuple& t, port_ref_impl<N1, N2>(* fn)(), Args1&... args1, Args2&... args2) {
doit_impl(x, f, t, fn(), args1..., args2...);
}
template <typename F, typename Tuple, int N, typename ...Args2>
static void doit_impl(std::true_type x, F& f, Tuple& t, port_ref_impl<N, N>(* fn)(), Args1&... args1, Args2&... args2) {
doit_impl(x, f, t, fn(), args1..., args2...);
}
};
template <>
struct convert_and_call_impl<> {
template <typename F, typename Tuple, typename ...Args2>
static void doit(F& f, Tuple&, Args2&... args2) {
f(args2...);
}
};
// ------------------------------------------- //
template<typename JP, typename StreamFactory, typename... Ports>
struct streaming_node_traits {
// Do not use 'using' instead of 'struct' because Microsoft Visual C++ 12.0 fails to compile.
template <typename T>
struct async_msg_type {
typedef typename StreamFactory::template async_msg_type<T> type;
};
typedef tuple< typename async_msg_type<Ports>::type... > input_tuple;
typedef input_tuple output_tuple;
typedef tuple< streaming_device_with_key< typename StreamFactory::device_type, typename key_from_policy<JP>::type >,
typename async_msg_type<Ports>::type... > kernel_input_tuple;
// indexer_node parameters pack expansion workaround for VS2013 for streaming_node
typedef indexer_node< typename async_msg_type<Ports>::type... > indexer_node_type;
};
// Default empty implementation
template<typename StreamFactory, typename KernelInputTuple, typename = void>
class kernel_executor_helper {
typedef typename StreamFactory::device_type device_type;
typedef typename StreamFactory::kernel_type kernel_type;
typedef KernelInputTuple kernel_input_tuple;
protected:
template <typename ...Args>
void enqueue_kernel_impl( kernel_input_tuple&, StreamFactory& factory, device_type device, const kernel_type& kernel, Args&... args ) const {
factory.send_kernel( device, kernel, args... );
}
};
// Implementation for StreamFactory supporting range
template<typename StreamFactory, typename KernelInputTuple>
class kernel_executor_helper<StreamFactory, KernelInputTuple, typename tbb::internal::void_t< typename StreamFactory::range_type >::type > {
typedef typename StreamFactory::device_type device_type;
typedef typename StreamFactory::kernel_type kernel_type;
typedef KernelInputTuple kernel_input_tuple;
typedef typename StreamFactory::range_type range_type;
// Container for randge. It can contain either port references or real range.
struct range_wrapper {
virtual range_type get_range( const kernel_input_tuple &ip ) const = 0;
virtual range_wrapper *clone() const = 0;
virtual ~range_wrapper() {}
};
struct range_value : public range_wrapper {
range_value( const range_type& value ) : my_value(value) {}
range_value( range_type&& value ) : my_value(std::move(value)) {}
range_type get_range( const kernel_input_tuple & ) const __TBB_override {
return my_value;
}
range_wrapper *clone() const __TBB_override {
return new range_value(my_value);
}
private:
range_type my_value;
};
template <int N>
struct range_mapper : public range_wrapper {
range_mapper() {}
range_type get_range( const kernel_input_tuple &ip ) const __TBB_override {
// "+1" since get<0>(ip) is StreamFactory::device.
return get<N + 1>(ip).data(false);
}
range_wrapper *clone() const __TBB_override {
return new range_mapper<N>;
}
};
protected:
template <typename ...Args>
void enqueue_kernel_impl( kernel_input_tuple& ip, StreamFactory& factory, device_type device, const kernel_type& kernel, Args&... args ) const {
__TBB_ASSERT(my_range_wrapper, "Range is not set. Call set_range() before running streaming_node.");
factory.send_kernel( device, kernel, my_range_wrapper->get_range(ip), args... );
}
public:
kernel_executor_helper() : my_range_wrapper(NULL) {}
kernel_executor_helper(const kernel_executor_helper& executor) : my_range_wrapper(executor.my_range_wrapper ? executor.my_range_wrapper->clone() : NULL) {}
kernel_executor_helper(kernel_executor_helper&& executor) : my_range_wrapper(executor.my_range_wrapper) {
// Set moving holder mappers to NULL to prevent double deallocation
executor.my_range_wrapper = NULL;
}
~kernel_executor_helper() {
if (my_range_wrapper) delete my_range_wrapper;
}
void set_range(const range_type& work_size) {
my_range_wrapper = new range_value(work_size);
}
void set_range(range_type&& work_size) {
my_range_wrapper = new range_value(std::move(work_size));
}
template <int N>
void set_range(port_ref_impl<N, N>) {
my_range_wrapper = new range_mapper<N>;
}
template <int N>
void set_range(port_ref_impl<N, N>(*)()) {
my_range_wrapper = new range_mapper<N>;
}
private:
range_wrapper* my_range_wrapper;
};
} // internal
/*
/---------------------------------------- streaming_node ------------------------------------\
| |
| /--------------\ /----------------------\ /-----------\ /----------------------\ |
| | | | (device_with_key) O---O | | | |
| | | | | | | | | |
O---O indexer_node O---O device_selector_node O---O join_node O---O kernel_node O---O
| | | | (multifunction_node) | | | | (multifunction_node) | |
O---O | | O---O | | O---O
| \--------------/ \----------------------/ \-----------/ \----------------------/ |
| |
\--------------------------------------------------------------------------------------------/
*/
template<typename... Args>
class streaming_node;
template<typename... Ports, typename JP, typename StreamFactory>
class streaming_node< tuple<Ports...>, JP, StreamFactory >
: public composite_node < typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::input_tuple,
typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::output_tuple >
, public internal::kernel_executor_helper< StreamFactory, typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::kernel_input_tuple >
{
typedef typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::input_tuple input_tuple;
typedef typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::output_tuple output_tuple;
typedef typename internal::key_from_policy<JP>::type key_type;
protected:
typedef typename StreamFactory::device_type device_type;
typedef typename StreamFactory::kernel_type kernel_type;
private:
typedef internal::streaming_device_with_key<device_type, key_type> device_with_key_type;
typedef composite_node<input_tuple, output_tuple> base_type;
static const size_t NUM_INPUTS = tuple_size<input_tuple>::value;
static const size_t NUM_OUTPUTS = tuple_size<output_tuple>::value;
typedef typename internal::make_sequence<NUM_INPUTS>::type input_sequence;
typedef typename internal::make_sequence<NUM_OUTPUTS>::type output_sequence;
typedef typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::indexer_node_type indexer_node_type;
typedef typename indexer_node_type::output_type indexer_node_output_type;
typedef typename internal::streaming_node_traits<JP, StreamFactory, Ports...>::kernel_input_tuple kernel_input_tuple;
typedef multifunction_node<indexer_node_output_type, kernel_input_tuple> device_selector_node;
typedef multifunction_node<kernel_input_tuple, output_tuple> kernel_multifunction_node;
template <int... S>
typename base_type::input_ports_type get_input_ports( internal::sequence<S...> ) {
return std::tie( internal::input_port<S>( my_indexer_node )... );
}
template <int... S>
typename base_type::output_ports_type get_output_ports( internal::sequence<S...> ) {
return std::tie( internal::output_port<S>( my_kernel_node )... );
}
typename base_type::input_ports_type get_input_ports() {
return get_input_ports( input_sequence() );
}
typename base_type::output_ports_type get_output_ports() {
return get_output_ports( output_sequence() );
}
template <int N>
int make_Nth_edge() {
make_edge( internal::output_port<N>( my_device_selector_node ), internal::input_port<N>( my_join_node ) );
return 0;
}
template <int... S>
void make_edges( internal::sequence<S...> ) {
make_edge( my_indexer_node, my_device_selector_node );
make_edge( my_device_selector_node, my_join_node );
internal::ignore_return_values( make_Nth_edge<S + 1>()... );
make_edge( my_join_node, my_kernel_node );
}
void make_edges() {
make_edges( input_sequence() );
}
class device_selector_base {
public:
virtual void operator()( const indexer_node_output_type &v, typename device_selector_node::output_ports_type &op ) = 0;
virtual device_selector_base *clone( streaming_node &n ) const = 0;
virtual ~device_selector_base() {}
};
template <typename UserFunctor>
class device_selector : public device_selector_base, tbb::internal::no_assign {
public:
device_selector( UserFunctor uf, streaming_node &n, StreamFactory &f )
: my_dispatch_funcs( create_dispatch_funcs( input_sequence() ) )
, my_user_functor( uf ), my_node(n), my_factory( f )
{
my_port_epoches.fill( 0 );
}
void operator()( const indexer_node_output_type &v, typename device_selector_node::output_ports_type &op ) __TBB_override {
(this->*my_dispatch_funcs[ v.tag() ])( my_port_epoches[ v.tag() ], v, op );
__TBB_ASSERT( (tbb::internal::is_same_type<typename internal::key_from_policy<JP>::is_key_matching, std::false_type>::value)
|| my_port_epoches[v.tag()] == 0, "Epoch is changed when key matching is requested" );
}
device_selector_base *clone( streaming_node &n ) const __TBB_override {
return new device_selector( my_user_functor, n, my_factory );
}
private:
typedef void(device_selector<UserFunctor>::*send_and_put_fn_type)(size_t &, const indexer_node_output_type &, typename device_selector_node::output_ports_type &);
typedef std::array < send_and_put_fn_type, NUM_INPUTS > dispatch_funcs_type;
template <int... S>
static dispatch_funcs_type create_dispatch_funcs( internal::sequence<S...> ) {
dispatch_funcs_type dispatch = { { &device_selector<UserFunctor>::send_and_put_impl<S>... } };
return dispatch;
}
template <typename T>
key_type get_key( std::false_type, const T &, size_t &epoch ) {
__TBB_STATIC_ASSERT( (tbb::internal::is_same_type<key_type, size_t>::value), "" );
return epoch++;
}
template <typename T>
key_type get_key( std::true_type, const T &t, size_t &/*epoch*/ ) {
using tbb::flow::key_from_message;
return key_from_message<key_type>( t );
}
template <int N>
void send_and_put_impl( size_t &epoch, const indexer_node_output_type &v, typename device_selector_node::output_ports_type &op ) {
typedef typename tuple_element<N + 1, typename device_selector_node::output_ports_type>::type::output_type elem_type;
elem_type e = internal::cast_to<elem_type>( v );
device_type device = get_device( get_key( typename internal::key_from_policy<JP>::is_key_matching(), e, epoch ), get<0>( op ) );
my_factory.send_data( device, e );
get<N + 1>( op ).try_put( e );
}
template< typename DevicePort >
device_type get_device( key_type key, DevicePort& dp ) {
typename std::unordered_map<typename std::decay<key_type>::type, epoch_desc>::iterator it = my_devices.find( key );
if ( it == my_devices.end() ) {
device_type d = my_user_functor( my_factory );
std::tie( it, std::ignore ) = my_devices.insert( std::make_pair( key, d ) );
bool res = dp.try_put( device_with_key_type( d, key ) );
__TBB_ASSERT_EX( res, NULL );
my_node.notify_new_device( d );
}
epoch_desc &e = it->second;
device_type d = e.my_device;
if ( ++e.my_request_number == NUM_INPUTS ) my_devices.erase( it );
return d;
}
struct epoch_desc {
epoch_desc(device_type d ) : my_device( d ), my_request_number( 0 ) {}
device_type my_device;
size_t my_request_number;
};
std::unordered_map<typename std::decay<key_type>::type, epoch_desc> my_devices;
std::array<size_t, NUM_INPUTS> my_port_epoches;
dispatch_funcs_type my_dispatch_funcs;
UserFunctor my_user_functor;
streaming_node &my_node;
StreamFactory &my_factory;
};
class device_selector_body {
public:
device_selector_body( device_selector_base *d ) : my_device_selector( d ) {}
void operator()( const indexer_node_output_type &v, typename device_selector_node::output_ports_type &op ) {
(*my_device_selector)(v, op);
}
private:
device_selector_base *my_device_selector;
};
class args_storage_base : tbb::internal::no_copy {
public:
typedef typename kernel_multifunction_node::output_ports_type output_ports_type;
virtual void enqueue( kernel_input_tuple &ip, output_ports_type &op, const streaming_node &n ) = 0;
virtual void send( device_type d ) = 0;
virtual args_storage_base *clone() const = 0;
virtual ~args_storage_base () {}
protected:
args_storage_base( const kernel_type& kernel, StreamFactory &f )
: my_kernel( kernel ), my_factory( f )
{}
args_storage_base( const args_storage_base &k )
: my_kernel( k.my_kernel ), my_factory( k.my_factory )
{}
const kernel_type my_kernel;
StreamFactory &my_factory;
};
template <typename... Args>
class args_storage : public args_storage_base {
typedef typename args_storage_base::output_ports_type output_ports_type;
// ---------- Update events helpers ---------- //
template <int N>
bool do_try_put( const kernel_input_tuple& ip, output_ports_type &op ) const {
const auto& t = get<N + 1>( ip );
auto &port = get<N>( op );
return port.try_put( t );
}
template <int... S>
bool do_try_put( const kernel_input_tuple& ip, output_ports_type &op, internal::sequence<S...> ) const {
return internal::or_return_values( do_try_put<S>( ip, op )... );
}
// ------------------------------------------- //
class run_kernel_func : tbb::internal::no_assign {
public:
run_kernel_func( kernel_input_tuple &ip, const streaming_node &node, const args_storage& storage )
: my_kernel_func( ip, node, storage, get<0>(ip).device() ) {}
// It is immpossible to use Args... because a function pointer cannot be casted to a function reference implicitly.
// Allow the compiler to deduce types for function pointers automatically.
template <typename... FnArgs>
void operator()( FnArgs&... args ) {
internal::convert_and_call_impl<FnArgs...>::doit( my_kernel_func, my_kernel_func.my_ip, args... );
}
private:
struct kernel_func : tbb::internal::no_copy {
kernel_input_tuple &my_ip;
const streaming_node &my_node;
const args_storage& my_storage;
device_type my_device;
kernel_func( kernel_input_tuple &ip, const streaming_node &node, const args_storage& storage, device_type device )
: my_ip( ip ), my_node( node ), my_storage( storage ), my_device( device )
{}
template <typename... FnArgs>
void operator()( FnArgs&... args ) {
my_node.enqueue_kernel( my_ip, my_storage.my_factory, my_device, my_storage.my_kernel, args... );
}
} my_kernel_func;
};
template<typename FinalizeFn>
class run_finalize_func : tbb::internal::no_assign {
public:
run_finalize_func( kernel_input_tuple &ip, StreamFactory &factory, FinalizeFn fn )
: my_ip( ip ), my_finalize_func( factory, get<0>(ip).device(), fn ) {}
// It is immpossible to use Args... because a function pointer cannot be casted to a function reference implicitly.
// Allow the compiler to deduce types for function pointers automatically.
template <typename... FnArgs>
void operator()( FnArgs&... args ) {
internal::convert_and_call_impl<FnArgs...>::doit( my_finalize_func, my_ip, args... );
}
private:
kernel_input_tuple &my_ip;
struct finalize_func : tbb::internal::no_assign {
StreamFactory &my_factory;
device_type my_device;
FinalizeFn my_fn;
finalize_func( StreamFactory &factory, device_type device, FinalizeFn fn )
: my_factory(factory), my_device(device), my_fn(fn) {}
template <typename... FnArgs>
void operator()( FnArgs&... args ) {
my_factory.finalize( my_device, my_fn, args... );
}
} my_finalize_func;
};
template<typename FinalizeFn>
static run_finalize_func<FinalizeFn> make_run_finalize_func( kernel_input_tuple &ip, StreamFactory &factory, FinalizeFn fn ) {
return run_finalize_func<FinalizeFn>( ip, factory, fn );
}
class send_func : tbb::internal::no_assign {
public:
send_func( StreamFactory &factory, device_type d )
: my_factory(factory), my_device( d ) {}
template <typename... FnArgs>
void operator()( FnArgs&... args ) {
my_factory.send_data( my_device, args... );
}
private:
StreamFactory &my_factory;
device_type my_device;
};
public:
args_storage( const kernel_type& kernel, StreamFactory &f, Args&&... args )
: args_storage_base( kernel, f )
, my_args_pack( std::forward<Args>(args)... )
{}
args_storage( const args_storage &k ) : args_storage_base( k ), my_args_pack( k.my_args_pack ) {}
args_storage( const args_storage_base &k, Args&&... args ) : args_storage_base( k ), my_args_pack( std::forward<Args>(args)... ) {}
void enqueue( kernel_input_tuple &ip, output_ports_type &op, const streaming_node &n ) __TBB_override {
// Make const qualified args_pack (from non-const)
const args_pack_type& const_args_pack = my_args_pack;
// factory.enqure_kernel() gets
// - 'ip' tuple elements by reference and updates it (and 'ip') with dependencies
// - arguments (from my_args_pack) by const-reference via const_args_pack
tbb::internal::call( run_kernel_func( ip, n, *this ), const_args_pack );
if (! do_try_put( ip, op, input_sequence() ) ) {
graph& g = n.my_graph;
// No one message was passed to successors so set a callback to extend the graph lifetime until the kernel completion.
g.increment_wait_count();
// factory.finalize() gets
// - 'ip' tuple elements by reference, so 'ip' might be changed
// - arguments (from my_args_pack) by const-reference via const_args_pack
tbb::internal::call( make_run_finalize_func(ip, this->my_factory, [&g] {
g.decrement_wait_count();
}), const_args_pack );
}
}
void send( device_type d ) __TBB_override {
// factory.send() gets arguments by reference and updates these arguments with dependencies
// (it gets but usually ignores port_ref-s)
tbb::internal::call( send_func( this->my_factory, d ), my_args_pack );
}
args_storage_base *clone() const __TBB_override {
// Create new args_storage with copying constructor.
return new args_storage<Args...>( *this );
}
private:
typedef tbb::internal::stored_pack<Args...> args_pack_type;
args_pack_type my_args_pack;
};
// Body for kernel_multifunction_node.
class kernel_body : tbb::internal::no_assign {
public:
kernel_body( const streaming_node &node ) : my_node( node ) {}
void operator()( kernel_input_tuple ip, typename args_storage_base::output_ports_type &op ) {
__TBB_ASSERT( (my_node.my_args_storage != NULL), "No arguments storage" );
// 'ip' is passed by value to create local copy for updating inside enqueue_kernel()
my_node.my_args_storage->enqueue( ip, op, my_node );
}
private:
const streaming_node &my_node;
};
template <typename T, typename U = typename internal::is_port_ref<T>::type >
struct wrap_to_async {
typedef T type; // Keep port_ref as it is
};
template <typename T>
struct wrap_to_async<T, std::false_type> {
typedef typename StreamFactory::template async_msg_type< typename tbb::internal::strip<T>::type > type;
};
template <typename... Args>
args_storage_base *make_args_storage(const args_storage_base& storage, Args&&... args) const {
// In this variadic template convert all simple types 'T' into 'async_msg_type<T>'
return new args_storage<Args...>(storage, std::forward<Args>(args)...);
}
void notify_new_device( device_type d ) {
my_args_storage->send( d );
}
template <typename ...Args>
void enqueue_kernel( kernel_input_tuple& ip, StreamFactory& factory, device_type device, const kernel_type& kernel, Args&... args ) const {
this->enqueue_kernel_impl( ip, factory, device, kernel, args... );
}
public:
template <typename DeviceSelector>
streaming_node( graph &g, const kernel_type& kernel, DeviceSelector d, StreamFactory &f )
: base_type( g )
, my_indexer_node( g )
, my_device_selector( new device_selector<DeviceSelector>( d, *this, f ) )
, my_device_selector_node( g, serial, device_selector_body( my_device_selector ) )
, my_join_node( g )
, my_kernel_node( g, serial, kernel_body( *this ) )
// By default, streaming_node maps all its ports to the kernel arguments on a one-to-one basis.
, my_args_storage( make_args_storage( args_storage<>(kernel, f), port_ref<0, NUM_INPUTS - 1>() ) )
{
base_type::set_external_ports( get_input_ports(), get_output_ports() );
make_edges();
}
streaming_node( const streaming_node &node )
: base_type( node.my_graph )
, my_indexer_node( node.my_indexer_node )
, my_device_selector( node.my_device_selector->clone( *this ) )
, my_device_selector_node( node.my_graph, serial, device_selector_body( my_device_selector ) )
, my_join_node( node.my_join_node )
, my_kernel_node( node.my_graph, serial, kernel_body( *this ) )
, my_args_storage( node.my_args_storage->clone() )
{
base_type::set_external_ports( get_input_ports(), get_output_ports() );
make_edges();
}
streaming_node( streaming_node &&node )
: base_type( node.my_graph )
, my_indexer_node( std::move( node.my_indexer_node ) )
, my_device_selector( node.my_device_selector->clone(*this) )
, my_device_selector_node( node.my_graph, serial, device_selector_body( my_device_selector ) )
, my_join_node( std::move( node.my_join_node ) )
, my_kernel_node( node.my_graph, serial, kernel_body( *this ) )
, my_args_storage( node.my_args_storage )
{
base_type::set_external_ports( get_input_ports(), get_output_ports() );
make_edges();
// Set moving node mappers to NULL to prevent double deallocation.
node.my_args_storage = NULL;
}
~streaming_node() {
if ( my_args_storage ) delete my_args_storage;
if ( my_device_selector ) delete my_device_selector;
}
template <typename... Args>
void set_args( Args&&... args ) {
// Copy the base class of args_storage and create new storage for "Args...".
args_storage_base * const new_args_storage = make_args_storage( *my_args_storage, typename wrap_to_async<Args>::type(std::forward<Args>(args))...);
delete my_args_storage;
my_args_storage = new_args_storage;
}
protected:
void reset_node( reset_flags = rf_reset_protocol ) __TBB_override { __TBB_ASSERT( false, "Not implemented yet" ); }
private:
indexer_node_type my_indexer_node;
device_selector_base *my_device_selector;
device_selector_node my_device_selector_node;
join_node<kernel_input_tuple, JP> my_join_node;
kernel_multifunction_node my_kernel_node;
args_storage_base *my_args_storage;
};
#endif // __TBB_PREVIEW_STREAMING_NODE
#endif // __TBB_flow_graph_streaming_H
@@ -0,0 +1,253 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// a hash table buffer that can expand, and can support as many deletions as
// additions, list-based, with elements of list held in array (for destruction
// management), multiplicative hashing (like ets). No synchronization built-in.
//
#ifndef __TBB__flow_graph_hash_buffer_impl_H
#define __TBB__flow_graph_hash_buffer_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
// included in namespace tbb::flow::interfaceX::internal
// elements in the table are a simple list; we need pointer to next element to
// traverse the chain
template<typename ValueType>
struct buffer_element_type {
// the second parameter below is void * because we can't forward-declare the type
// itself, so we just reinterpret_cast below.
typedef typename aligned_pair<ValueType, void *>::type type;
};
template
<
typename Key, // type of key within ValueType
typename ValueType,
typename ValueToKey, // abstract method that returns "const Key" or "const Key&" given ValueType
typename HashCompare, // has hash and equal
typename Allocator=tbb::cache_aligned_allocator< typename aligned_pair<ValueType, void *>::type >
>
class hash_buffer : public HashCompare {
public:
static const size_t INITIAL_SIZE = 8; // initial size of the hash pointer table
typedef ValueType value_type;
typedef typename buffer_element_type< value_type >::type element_type;
typedef value_type *pointer_type;
typedef element_type *list_array_type; // array we manage manually
typedef list_array_type *pointer_array_type;
typedef typename Allocator::template rebind<list_array_type>::other pointer_array_allocator_type;
typedef typename Allocator::template rebind<element_type>::other elements_array_allocator;
typedef typename tbb::internal::strip<Key>::type Knoref;
private:
ValueToKey *my_key;
size_t my_size;
size_t nelements;
pointer_array_type pointer_array; // pointer_array[my_size]
list_array_type elements_array; // elements_array[my_size / 2]
element_type* free_list;
size_t mask() { return my_size - 1; }
void set_up_free_list( element_type **p_free_list, list_array_type la, size_t sz) {
for(size_t i=0; i < sz - 1; ++i ) { // construct free list
la[i].second = &(la[i+1]);
}
la[sz-1].second = NULL;
*p_free_list = (element_type *)&(la[0]);
}
// cleanup for exceptions
struct DoCleanup {
pointer_array_type *my_pa;
list_array_type *my_elements;
size_t my_size;
DoCleanup(pointer_array_type &pa, list_array_type &my_els, size_t sz) :
my_pa(&pa), my_elements(&my_els), my_size(sz) { }
~DoCleanup() {
if(my_pa) {
size_t dont_care = 0;
internal_free_buffer(*my_pa, *my_elements, my_size, dont_care);
}
}
};
// exception-safety requires we do all the potentially-throwing operations first
void grow_array() {
size_t new_size = my_size*2;
size_t new_nelements = nelements; // internal_free_buffer zeroes this
list_array_type new_elements_array = NULL;
pointer_array_type new_pointer_array = NULL;
list_array_type new_free_list = NULL;
{
DoCleanup my_cleanup(new_pointer_array, new_elements_array, new_size);
new_elements_array = elements_array_allocator().allocate(my_size);
new_pointer_array = pointer_array_allocator_type().allocate(new_size);
for(size_t i=0; i < new_size; ++i) new_pointer_array[i] = NULL;
set_up_free_list(&new_free_list, new_elements_array, my_size );
for(size_t i=0; i < my_size; ++i) {
for( element_type* op = pointer_array[i]; op; op = (element_type *)(op->second)) {
value_type *ov = reinterpret_cast<value_type *>(&(op->first));
// could have std::move semantics
internal_insert_with_key(new_pointer_array, new_size, new_free_list, *ov);
}
}
my_cleanup.my_pa = NULL;
my_cleanup.my_elements = NULL;
}
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
free_list = new_free_list;
pointer_array = new_pointer_array;
elements_array = new_elements_array;
my_size = new_size;
nelements = new_nelements;
}
// v should have perfect forwarding if std::move implemented.
// we use this method to move elements in grow_array, so can't use class fields
void internal_insert_with_key( element_type **p_pointer_array, size_t p_sz, list_array_type &p_free_list,
const value_type &v) {
size_t l_mask = p_sz-1;
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
size_t h = this->hash((*my_key)(v)) & l_mask;
__TBB_ASSERT(p_free_list, "Error: free list not set up.");
element_type* my_elem = p_free_list; p_free_list = (element_type *)(p_free_list->second);
(void) new(&(my_elem->first)) value_type(v);
my_elem->second = p_pointer_array[h];
p_pointer_array[h] = my_elem;
}
void internal_initialize_buffer() {
pointer_array = pointer_array_allocator_type().allocate(my_size);
for(size_t i = 0; i < my_size; ++i) pointer_array[i] = NULL;
elements_array = elements_array_allocator().allocate(my_size / 2);
set_up_free_list(&free_list, elements_array, my_size / 2);
}
// made static so an enclosed class can use to properly dispose of the internals
static void internal_free_buffer( pointer_array_type &pa, list_array_type &el, size_t &sz, size_t &ne ) {
if(pa) {
for(size_t i = 0; i < sz; ++i ) {
element_type *p_next;
for( element_type *p = pa[i]; p; p = p_next) {
p_next = (element_type *)p->second;
internal::punned_cast<value_type *>(&(p->first))->~value_type();
}
}
pointer_array_allocator_type().deallocate(pa, sz);
pa = NULL;
}
// Separate test (if allocation of pa throws, el may be allocated.
// but no elements will be constructed.)
if(el) {
elements_array_allocator().deallocate(el, sz / 2);
el = NULL;
}
sz = INITIAL_SIZE;
ne = 0;
}
public:
hash_buffer() : my_key(NULL), my_size(INITIAL_SIZE), nelements(0) {
internal_initialize_buffer();
}
~hash_buffer() {
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
if(my_key) delete my_key;
}
void reset() {
internal_free_buffer(pointer_array, elements_array, my_size, nelements);
internal_initialize_buffer();
}
// Take ownership of func object allocated with new.
// This method is only used internally, so can't be misused by user.
void set_key_func(ValueToKey *vtk) { my_key = vtk; }
// pointer is used to clone()
ValueToKey* get_key_func() { return my_key; }
bool insert_with_key(const value_type &v) {
pointer_type p = NULL;
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(find_ref_with_key((*my_key)(v), p)) {
p->~value_type();
(void) new(p) value_type(v); // copy-construct into the space
return false;
}
++nelements;
if(nelements*2 > my_size) grow_array();
internal_insert_with_key(pointer_array, my_size, free_list, v);
return true;
}
// returns true and sets v to array element if found, else returns false.
bool find_ref_with_key(const Knoref& k, pointer_type &v) {
size_t i = this->hash(k) & mask();
for(element_type* p = pointer_array[i]; p; p = (element_type *)(p->second)) {
pointer_type pv = reinterpret_cast<pointer_type>(&(p->first));
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(this->equal((*my_key)(*pv), k)) {
v = pv;
return true;
}
}
return false;
}
bool find_with_key( const Knoref& k, value_type &v) {
value_type *p;
if(find_ref_with_key(k, p)) {
v = *p;
return true;
}
else
return false;
}
void delete_with_key(const Knoref& k) {
size_t h = this->hash(k) & mask();
element_type* prev = NULL;
for(element_type* p = pointer_array[h]; p; prev = p, p = (element_type *)(p->second)) {
value_type *vp = reinterpret_cast<value_type *>(&(p->first));
__TBB_ASSERT(my_key, "Error: value-to-key functor not provided");
if(this->equal((*my_key)(*vp), k)) {
vp->~value_type();
if(prev) prev->second = p->second;
else pointer_array[h] = (element_type *)(p->second);
p->second = free_list;
free_list = p;
--nelements;
return;
}
}
__TBB_ASSERT(false, "key not found for delete");
}
};
#endif // __TBB__flow_graph_hash_buffer_impl_H
@@ -0,0 +1,307 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _FGT_GRAPH_TRACE_IMPL_H
#define _FGT_GRAPH_TRACE_IMPL_H
#include "../tbb_profiling.h"
namespace tbb {
namespace internal {
#if TBB_PREVIEW_FLOW_GRAPH_TRACE
static inline void fgt_internal_alias_input_port( void *node, void *p, string_index name_index ) {
itt_make_task_group( ITT_DOMAIN_FLOW, p, FLOW_INPUT_PORT, node, FLOW_NODE, name_index );
itt_relation_add( ITT_DOMAIN_FLOW, node, FLOW_NODE, __itt_relation_is_parent_of, p, FLOW_INPUT_PORT );
}
static inline void fgt_internal_alias_output_port( void *node, void *p, string_index name_index ) {
itt_make_task_group( ITT_DOMAIN_FLOW, p, FLOW_OUTPUT_PORT, node, FLOW_NODE, name_index );
itt_relation_add( ITT_DOMAIN_FLOW, node, FLOW_NODE, __itt_relation_is_parent_of, p, FLOW_OUTPUT_PORT );
}
template<typename InputType>
void alias_input_port(void *node, tbb::flow::receiver<InputType>* port, string_index name_index) {
// TODO: Make fgt_internal_alias_input_port a function template?
fgt_internal_alias_input_port( node, port, name_index);
}
template < typename PortsTuple, int N >
struct fgt_internal_input_alias_helper {
static void alias_port( void *node, PortsTuple &ports ) {
alias_input_port( node, &(tbb::flow::get<N-1>(ports)), static_cast<tbb::internal::string_index>(FLOW_INPUT_PORT_0 + N - 1) );
fgt_internal_input_alias_helper<PortsTuple, N-1>::alias_port( node, ports );
}
};
template < typename PortsTuple >
struct fgt_internal_input_alias_helper<PortsTuple, 0> {
static void alias_port( void * /* node */, PortsTuple & /* ports */ ) { }
};
template<typename OutputType>
void alias_output_port(void *node, tbb::flow::sender<OutputType>* port, string_index name_index) {
// TODO: Make fgt_internal_alias_output_port a function template?
fgt_internal_alias_output_port( node, static_cast<void *>(port), name_index);
}
template < typename PortsTuple, int N >
struct fgt_internal_output_alias_helper {
static void alias_port( void *node, PortsTuple &ports ) {
alias_output_port( node, &(tbb::flow::get<N-1>(ports)), static_cast<tbb::internal::string_index>(FLOW_OUTPUT_PORT_0 + N - 1) );
fgt_internal_output_alias_helper<PortsTuple, N-1>::alias_port( node, ports );
}
};
template < typename PortsTuple >
struct fgt_internal_output_alias_helper<PortsTuple, 0> {
static void alias_port( void * /*node*/, PortsTuple &/*ports*/ ) {
}
};
static inline void fgt_internal_create_input_port( void *node, void *p, string_index name_index ) {
itt_make_task_group( ITT_DOMAIN_FLOW, p, FLOW_INPUT_PORT, node, FLOW_NODE, name_index );
}
static inline void fgt_internal_create_output_port( void *node, void *p, string_index name_index ) {
itt_make_task_group( ITT_DOMAIN_FLOW, p, FLOW_OUTPUT_PORT, node, FLOW_NODE, name_index );
}
template<typename InputType>
void register_input_port(void *node, tbb::flow::receiver<InputType>* port, string_index name_index) {
// TODO: Make fgt_internal_create_input_port a function template?
// In C++03 dependent name lookup from the template definition context
// works only for function declarations with external linkage:
// http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#561
fgt_internal_create_input_port(node, static_cast<void*>(port), name_index);
}
template < typename PortsTuple, int N >
struct fgt_internal_input_helper {
static void register_port( void *node, PortsTuple &ports ) {
register_input_port( node, &(tbb::flow::get<N-1>(ports)), static_cast<tbb::internal::string_index>(FLOW_INPUT_PORT_0 + N - 1) );
fgt_internal_input_helper<PortsTuple, N-1>::register_port( node, ports );
}
};
template < typename PortsTuple >
struct fgt_internal_input_helper<PortsTuple, 1> {
static void register_port( void *node, PortsTuple &ports ) {
register_input_port( node, &(tbb::flow::get<0>(ports)), FLOW_INPUT_PORT_0 );
}
};
template<typename OutputType>
void register_output_port(void *node, tbb::flow::sender<OutputType>* port, string_index name_index) {
// TODO: Make fgt_internal_create_output_port a function template?
fgt_internal_create_output_port( node, static_cast<void *>(port), name_index);
}
template < typename PortsTuple, int N >
struct fgt_internal_output_helper {
static void register_port( void *node, PortsTuple &ports ) {
register_output_port( node, &(tbb::flow::get<N-1>(ports)), static_cast<tbb::internal::string_index>(FLOW_OUTPUT_PORT_0 + N - 1) );
fgt_internal_output_helper<PortsTuple, N-1>::register_port( node, ports );
}
};
template < typename PortsTuple >
struct fgt_internal_output_helper<PortsTuple,1> {
static void register_port( void *node, PortsTuple &ports ) {
register_output_port( node, &(tbb::flow::get<0>(ports)), FLOW_OUTPUT_PORT_0 );
}
};
template< typename NodeType >
void fgt_multioutput_node_desc( const NodeType *node, const char *desc ) {
void *addr = (void *)( static_cast< tbb::flow::receiver< typename NodeType::input_type > * >(const_cast< NodeType *>(node)) );
itt_metadata_str_add( ITT_DOMAIN_FLOW, addr, FLOW_NODE, FLOW_OBJECT_NAME, desc );
}
template< typename NodeType >
void fgt_multiinput_multioutput_node_desc( const NodeType *node, const char *desc ) {
void *addr = const_cast<NodeType *>(node);
itt_metadata_str_add( ITT_DOMAIN_FLOW, addr, FLOW_NODE, FLOW_OBJECT_NAME, desc );
}
template< typename NodeType >
static inline void fgt_node_desc( const NodeType *node, const char *desc ) {
void *addr = (void *)( static_cast< tbb::flow::sender< typename NodeType::output_type > * >(const_cast< NodeType *>(node)) );
itt_metadata_str_add( ITT_DOMAIN_FLOW, addr, FLOW_NODE, FLOW_OBJECT_NAME, desc );
}
static inline void fgt_graph_desc( void *g, const char *desc ) {
itt_metadata_str_add( ITT_DOMAIN_FLOW, g, FLOW_GRAPH, FLOW_OBJECT_NAME, desc );
}
static inline void fgt_body( void *node, void *body ) {
itt_relation_add( ITT_DOMAIN_FLOW, body, FLOW_BODY, __itt_relation_is_child_of, node, FLOW_NODE );
}
template< int N, typename PortsTuple >
static inline void fgt_multioutput_node( string_index t, void *g, void *input_port, PortsTuple &ports ) {
itt_make_task_group( ITT_DOMAIN_FLOW, input_port, FLOW_NODE, g, FLOW_GRAPH, t );
fgt_internal_create_input_port( input_port, input_port, FLOW_INPUT_PORT_0 );
fgt_internal_output_helper<PortsTuple, N>::register_port( input_port, ports );
}
template< int N, typename PortsTuple >
static inline void fgt_multioutput_node_with_body( string_index t, void *g, void *input_port, PortsTuple &ports, void *body ) {
itt_make_task_group( ITT_DOMAIN_FLOW, input_port, FLOW_NODE, g, FLOW_GRAPH, t );
fgt_internal_create_input_port( input_port, input_port, FLOW_INPUT_PORT_0 );
fgt_internal_output_helper<PortsTuple, N>::register_port( input_port, ports );
fgt_body( input_port, body );
}
template< int N, typename PortsTuple >
static inline void fgt_multiinput_node( string_index t, void *g, PortsTuple &ports, void *output_port) {
itt_make_task_group( ITT_DOMAIN_FLOW, output_port, FLOW_NODE, g, FLOW_GRAPH, t );
fgt_internal_create_output_port( output_port, output_port, FLOW_OUTPUT_PORT_0 );
fgt_internal_input_helper<PortsTuple, N>::register_port( output_port, ports );
}
static inline void fgt_multiinput_multioutput_node( string_index t, void *n, void *g ) {
itt_make_task_group( ITT_DOMAIN_FLOW, n, FLOW_NODE, g, FLOW_GRAPH, t );
}
static inline void fgt_node( string_index t, void *g, void *output_port ) {
itt_make_task_group( ITT_DOMAIN_FLOW, output_port, FLOW_NODE, g, FLOW_GRAPH, t );
fgt_internal_create_output_port( output_port, output_port, FLOW_OUTPUT_PORT_0 );
}
static inline void fgt_node_with_body( string_index t, void *g, void *output_port, void *body ) {
itt_make_task_group( ITT_DOMAIN_FLOW, output_port, FLOW_NODE, g, FLOW_GRAPH, t );
fgt_internal_create_output_port( output_port, output_port, FLOW_OUTPUT_PORT_0 );
fgt_body( output_port, body );
}
static inline void fgt_node( string_index t, void *g, void *input_port, void *output_port ) {
fgt_node( t, g, output_port );
fgt_internal_create_input_port( output_port, input_port, FLOW_INPUT_PORT_0 );
}
static inline void fgt_node_with_body( string_index t, void *g, void *input_port, void *output_port, void *body ) {
fgt_node_with_body( t, g, output_port, body );
fgt_internal_create_input_port( output_port, input_port, FLOW_INPUT_PORT_0 );
}
static inline void fgt_node( string_index t, void *g, void *input_port, void *decrement_port, void *output_port ) {
fgt_node( t, g, input_port, output_port );
fgt_internal_create_input_port( output_port, decrement_port, FLOW_INPUT_PORT_1 );
}
static inline void fgt_make_edge( void *output_port, void *input_port ) {
itt_relation_add( ITT_DOMAIN_FLOW, output_port, FLOW_OUTPUT_PORT, __itt_relation_is_predecessor_to, input_port, FLOW_INPUT_PORT);
}
static inline void fgt_remove_edge( void *output_port, void *input_port ) {
itt_relation_add( ITT_DOMAIN_FLOW, output_port, FLOW_OUTPUT_PORT, __itt_relation_is_sibling_of, input_port, FLOW_INPUT_PORT);
}
static inline void fgt_graph( void *g ) {
itt_make_task_group( ITT_DOMAIN_FLOW, g, FLOW_GRAPH, NULL, FLOW_NULL, FLOW_GRAPH );
}
static inline void fgt_begin_body( void *body ) {
itt_task_begin( ITT_DOMAIN_FLOW, body, FLOW_BODY, NULL, FLOW_NULL, FLOW_BODY );
}
static inline void fgt_end_body( void * ) {
itt_task_end( ITT_DOMAIN_FLOW );
}
static inline void fgt_async_try_put_begin( void *node, void *port ) {
itt_task_begin( ITT_DOMAIN_FLOW, port, FLOW_OUTPUT_PORT, node, FLOW_NODE, FLOW_OUTPUT_PORT );
}
static inline void fgt_async_try_put_end( void *, void * ) {
itt_task_end( ITT_DOMAIN_FLOW );
}
static inline void fgt_async_reserve( void *node, void *graph ) {
itt_region_begin( ITT_DOMAIN_FLOW, node, FLOW_NODE, graph, FLOW_GRAPH, FLOW_NULL );
}
static inline void fgt_async_commit( void *node, void */*graph*/) {
itt_region_end( ITT_DOMAIN_FLOW, node, FLOW_NODE );
}
static inline void fgt_reserve_wait( void *graph ) {
itt_region_begin( ITT_DOMAIN_FLOW, graph, FLOW_GRAPH, NULL, FLOW_NULL, FLOW_NULL );
}
static inline void fgt_release_wait( void *graph ) {
itt_region_end( ITT_DOMAIN_FLOW, graph, FLOW_GRAPH );
}
#else // TBB_PREVIEW_FLOW_GRAPH_TRACE
static inline void fgt_graph( void * /*g*/ ) { }
template< typename NodeType >
static inline void fgt_multioutput_node_desc( const NodeType * /*node*/, const char * /*desc*/ ) { }
template< typename NodeType >
static inline void fgt_node_desc( const NodeType * /*node*/, const char * /*desc*/ ) { }
static inline void fgt_graph_desc( void * /*g*/, const char * /*desc*/ ) { }
static inline void fgt_body( void * /*node*/, void * /*body*/ ) { }
template< int N, typename PortsTuple >
static inline void fgt_multioutput_node( string_index /*t*/, void * /*g*/, void * /*input_port*/, PortsTuple & /*ports*/ ) { }
template< int N, typename PortsTuple >
static inline void fgt_multioutput_node_with_body( string_index /*t*/, void * /*g*/, void * /*input_port*/, PortsTuple & /*ports*/, void * /*body*/ ) { }
template< int N, typename PortsTuple >
static inline void fgt_multiinput_node( string_index /*t*/, void * /*g*/, PortsTuple & /*ports*/, void * /*output_port*/ ) { }
static inline void fgt_multiinput_multioutput_node( string_index /*t*/, void * /*node*/, void * /*graph*/ ) { }
static inline void fgt_node( string_index /*t*/, void * /*g*/, void * /*output_port*/ ) { }
static inline void fgt_node( string_index /*t*/, void * /*g*/, void * /*input_port*/, void * /*output_port*/ ) { }
static inline void fgt_node( string_index /*t*/, void * /*g*/, void * /*input_port*/, void * /*decrement_port*/, void * /*output_port*/ ) { }
static inline void fgt_node_with_body( string_index /*t*/, void * /*g*/, void * /*output_port*/, void * /*body*/ ) { }
static inline void fgt_node_with_body( string_index /*t*/, void * /*g*/, void * /*input_port*/, void * /*output_port*/, void * /*body*/ ) { }
static inline void fgt_make_edge( void * /*output_port*/, void * /*input_port*/ ) { }
static inline void fgt_remove_edge( void * /*output_port*/, void * /*input_port*/ ) { }
static inline void fgt_begin_body( void * /*body*/ ) { }
static inline void fgt_end_body( void * /*body*/) { }
static inline void fgt_async_try_put_begin( void * /*node*/, void * /*port*/ ) { }
static inline void fgt_async_try_put_end( void * /*node*/ , void * /*port*/ ) { }
static inline void fgt_async_reserve( void * /*node*/, void * /*graph*/ ) { }
static inline void fgt_async_commit( void * /*node*/, void * /*graph*/ ) { }
static inline void fgt_reserve_wait( void * /*graph*/ ) { }
static inline void fgt_release_wait( void * /*graph*/ ) { }
#endif // TBB_PREVIEW_FLOW_GRAPH_TRACE
} // namespace internal
} // namespace tbb
#endif
@@ -0,0 +1,713 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__flow_graph_types_impl_H
#define __TBB__flow_graph_types_impl_H
#ifndef __TBB_flow_graph_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
// included in namespace tbb::flow::interfaceX
namespace internal {
// the change to key_matching (adding a K and KHash template parameter, making it a class)
// means we have to pass this data to the key_matching_port. All the ports have only one
// template parameter, so we have to wrap the following types in a trait:
//
// . K == key_type
// . KHash == hash and compare for Key
// . TtoK == function_body that given an object of T, returns its K
// . T == type accepted by port, and stored in the hash table
//
// The port will have an additional parameter on node construction, which is a function_body
// that accepts a const T& and returns a K which is the field in T which is its K.
template<typename Kp, typename KHashp, typename Tp>
struct KeyTrait {
typedef Kp K;
typedef Tp T;
typedef internal::type_to_key_function_body<T,K> TtoK;
typedef KHashp KHash;
};
// wrap each element of a tuple in a template, and make a tuple of the result.
template<int N, template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements;
// A wrapper that generates the traits needed for each port of a key-matching join,
// and the type of the tuple of input ports.
template<int N, template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements;
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<1, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<1, PT, KeyTraits, TypeTuple > {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef typename tbb::flow::tuple< PT<KeyTrait0> > type;
};
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<2, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<2, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1> > type;
};
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<3, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<3, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2> > type;
};
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<4, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<4, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>,
PT<KeyTrait3> > type;
};
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<5, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<5, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>,
PT<KeyTrait3>, PT<KeyTrait4> > type;
};
#if __TBB_VARIADIC_MAX >= 6
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<6, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<5,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<6, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<5,TypeTuple>::type> KeyTrait5;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>, PT<KeyTrait3>,
PT<KeyTrait4>, PT<KeyTrait5> > type;
};
#endif
#if __TBB_VARIADIC_MAX >= 7
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<7, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<5,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<6,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<7, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<5,TypeTuple>::type> KeyTrait5;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<6,TypeTuple>::type> KeyTrait6;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>, PT<KeyTrait3>,
PT<KeyTrait4>, PT<KeyTrait5>, PT<KeyTrait6> > type;
};
#endif
#if __TBB_VARIADIC_MAX >= 8
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<8, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<5,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<6,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<7,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<8, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<5,TypeTuple>::type> KeyTrait5;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<6,TypeTuple>::type> KeyTrait6;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<7,TypeTuple>::type> KeyTrait7;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>, PT<KeyTrait3>,
PT<KeyTrait4>, PT<KeyTrait5>, PT<KeyTrait6>, PT<KeyTrait7> > type;
};
#endif
#if __TBB_VARIADIC_MAX >= 9
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<9, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<5,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<6,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<7,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<8,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<9, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<5,TypeTuple>::type> KeyTrait5;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<6,TypeTuple>::type> KeyTrait6;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<7,TypeTuple>::type> KeyTrait7;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<8,TypeTuple>::type> KeyTrait8;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>, PT<KeyTrait3>,
PT<KeyTrait4>, PT<KeyTrait5>, PT<KeyTrait6>, PT<KeyTrait7>, PT<KeyTrait8> > type;
};
#endif
#if __TBB_VARIADIC_MAX >= 10
template<template<class> class PT, typename TypeTuple>
struct wrap_tuple_elements<10, PT, TypeTuple> {
typedef typename tbb::flow::tuple<
PT<typename tbb::flow::tuple_element<0,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<1,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<2,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<3,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<4,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<5,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<6,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<7,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<8,TypeTuple>::type>,
PT<typename tbb::flow::tuple_element<9,TypeTuple>::type> >
type;
};
template<template<class> class PT, typename KeyTraits, typename TypeTuple>
struct wrap_key_tuple_elements<10, PT, KeyTraits, TypeTuple> {
typedef typename KeyTraits::key_type K;
typedef typename KeyTraits::hash_compare_type KHash;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<0,TypeTuple>::type> KeyTrait0;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<1,TypeTuple>::type> KeyTrait1;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<2,TypeTuple>::type> KeyTrait2;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<3,TypeTuple>::type> KeyTrait3;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<4,TypeTuple>::type> KeyTrait4;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<5,TypeTuple>::type> KeyTrait5;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<6,TypeTuple>::type> KeyTrait6;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<7,TypeTuple>::type> KeyTrait7;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<8,TypeTuple>::type> KeyTrait8;
typedef KeyTrait<K, KHash, typename tbb::flow::tuple_element<9,TypeTuple>::type> KeyTrait9;
typedef typename tbb::flow::tuple< PT<KeyTrait0>, PT<KeyTrait1>, PT<KeyTrait2>, PT<KeyTrait3>,
PT<KeyTrait4>, PT<KeyTrait5>, PT<KeyTrait6>, PT<KeyTrait7>, PT<KeyTrait8>,
PT<KeyTrait9> > type;
};
#endif
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
template< int... S > class sequence {};
template< int N, int... S >
struct make_sequence : make_sequence < N - 1, N - 1, S... > {};
template< int... S >
struct make_sequence < 0, S... > {
typedef sequence<S...> type;
};
#endif /* __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT */
#if __TBB_INITIALIZER_LISTS_PRESENT
// Until C++14 std::initializer_list does not guarantee life time of contained objects.
template <typename T>
class initializer_list_wrapper {
public:
typedef T value_type;
typedef const T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef T* iterator;
typedef const T* const_iterator;
initializer_list_wrapper( std::initializer_list<T> il ) __TBB_NOEXCEPT( true ) : my_begin( static_cast<T*>(malloc( il.size()*sizeof( T ) )) ) {
iterator dst = my_begin;
for ( typename std::initializer_list<T>::const_iterator src = il.begin(); src != il.end(); ++src )
new (dst++) T( *src );
my_end = dst;
}
initializer_list_wrapper( const initializer_list_wrapper<T>& ilw ) __TBB_NOEXCEPT( true ) : my_begin( static_cast<T*>(malloc( ilw.size()*sizeof( T ) )) ) {
iterator dst = my_begin;
for ( typename std::initializer_list<T>::const_iterator src = ilw.begin(); src != ilw.end(); ++src )
new (dst++) T( *src );
my_end = dst;
}
#if __TBB_CPP11_RVALUE_REF_PRESENT
initializer_list_wrapper( initializer_list_wrapper<T>&& ilw ) __TBB_NOEXCEPT( true ) : my_begin( ilw.my_begin ), my_end( ilw.my_end ) {
ilw.my_begin = ilw.my_end = NULL;
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */
~initializer_list_wrapper() {
if ( my_begin )
free( my_begin );
}
const_iterator begin() const __TBB_NOEXCEPT(true) { return my_begin; }
const_iterator end() const __TBB_NOEXCEPT(true) { return my_end; }
size_t size() const __TBB_NOEXCEPT(true) { return (size_t)(my_end - my_begin); }
private:
iterator my_begin;
iterator my_end;
};
#endif /* __TBB_INITIALIZER_LISTS_PRESENT */
//! type mimicking std::pair but with trailing fill to ensure each element of an array
//* will have the correct alignment
template<typename T1, typename T2, size_t REM>
struct type_plus_align {
char first[sizeof(T1)];
T2 second;
char fill1[REM];
};
template<typename T1, typename T2>
struct type_plus_align<T1,T2,0> {
char first[sizeof(T1)];
T2 second;
};
template<class U> struct alignment_of {
typedef struct { char t; U padded; } test_alignment;
static const size_t value = sizeof(test_alignment) - sizeof(U);
};
// T1, T2 are actual types stored. The space defined for T1 in the type returned
// is a char array of the correct size. Type T2 should be trivially-constructible,
// T1 must be explicitly managed.
template<typename T1, typename T2>
struct aligned_pair {
static const size_t t1_align = alignment_of<T1>::value;
static const size_t t2_align = alignment_of<T2>::value;
typedef type_plus_align<T1, T2, 0 > just_pair;
static const size_t max_align = t1_align < t2_align ? t2_align : t1_align;
static const size_t extra_bytes = sizeof(just_pair) % max_align;
static const size_t remainder = extra_bytes ? max_align - extra_bytes : 0;
public:
typedef type_plus_align<T1,T2,remainder> type;
}; // aligned_pair
// support for variant type
// type we use when we're not storing a value
struct default_constructed { };
// type which contains another type, tests for what type is contained, and references to it.
// internal::Wrapper<T>
// void CopyTo( void *newSpace) : builds a Wrapper<T> copy of itself in newSpace
// struct to allow us to copy and test the type of objects
struct WrapperBase {
virtual ~WrapperBase() {}
virtual void CopyTo(void* /*newSpace*/) const { }
};
// Wrapper<T> contains a T, with the ability to test what T is. The Wrapper<T> can be
// constructed from a T, can be copy-constructed from another Wrapper<T>, and can be
// examined via value(), but not modified.
template<typename T>
struct Wrapper: public WrapperBase {
typedef T value_type;
typedef T* pointer_type;
private:
T value_space;
public:
const value_type &value() const { return value_space; }
private:
Wrapper();
// on exception will ensure the Wrapper will contain only a trivially-constructed object
struct _unwind_space {
pointer_type space;
_unwind_space(pointer_type p) : space(p) {}
~_unwind_space() {
if(space) (void) new (space) Wrapper<default_constructed>(default_constructed());
}
};
public:
explicit Wrapper( const T& other ) : value_space(other) { }
explicit Wrapper(const Wrapper& other) : value_space(other.value_space) { }
void CopyTo(void* newSpace) const __TBB_override {
_unwind_space guard((pointer_type)newSpace);
(void) new(newSpace) Wrapper(value_space);
guard.space = NULL;
}
~Wrapper() { }
};
// specialization for array objects
template<typename T, size_t N>
struct Wrapper<T[N]> : public WrapperBase {
typedef T value_type;
typedef T* pointer_type;
// space must be untyped.
typedef T ArrayType[N];
private:
// The space is not of type T[N] because when copy-constructing, it would be
// default-initialized and then copied to in some fashion, resulting in two
// constructions and one destruction per element. If the type is char[ ], we
// placement new into each element, resulting in one construction per element.
static const size_t space_size = sizeof(ArrayType) / sizeof(char);
char value_space[space_size];
// on exception will ensure the already-built objects will be destructed
// (the value_space is a char array, so it is already trivially-destructible.)
struct _unwind_class {
pointer_type space;
int already_built;
_unwind_class(pointer_type p) : space(p), already_built(0) {}
~_unwind_class() {
if(space) {
for(size_t i = already_built; i > 0 ; --i ) space[i-1].~value_type();
(void) new(space) Wrapper<default_constructed>(default_constructed());
}
}
};
public:
const ArrayType &value() const {
char *vp = const_cast<char *>(value_space);
return reinterpret_cast<ArrayType &>(*vp);
}
private:
Wrapper();
public:
// have to explicitly construct because other decays to a const value_type*
explicit Wrapper(const ArrayType& other) {
_unwind_class guard((pointer_type)value_space);
pointer_type vp = reinterpret_cast<pointer_type>(&value_space);
for(size_t i = 0; i < N; ++i ) {
(void) new(vp++) value_type(other[i]);
++(guard.already_built);
}
guard.space = NULL;
}
explicit Wrapper(const Wrapper& other) : WrapperBase() {
// we have to do the heavy lifting to copy contents
_unwind_class guard((pointer_type)value_space);
pointer_type dp = reinterpret_cast<pointer_type>(value_space);
pointer_type sp = reinterpret_cast<pointer_type>(const_cast<char *>(other.value_space));
for(size_t i = 0; i < N; ++i, ++dp, ++sp) {
(void) new(dp) value_type(*sp);
++(guard.already_built);
}
guard.space = NULL;
}
void CopyTo(void* newSpace) const __TBB_override {
(void) new(newSpace) Wrapper(*this); // exceptions handled in copy constructor
}
~Wrapper() {
// have to destroy explicitly in reverse order
pointer_type vp = reinterpret_cast<pointer_type>(&value_space);
for(size_t i = N; i > 0 ; --i ) vp[i-1].~value_type();
}
};
// given a tuple, return the type of the element that has the maximum alignment requirement.
// Given a tuple and that type, return the number of elements of the object with the max
// alignment requirement that is at least as big as the largest object in the tuple.
template<bool, class T1, class T2> struct pick_one;
template<class T1, class T2> struct pick_one<true , T1, T2> { typedef T1 type; };
template<class T1, class T2> struct pick_one<false, T1, T2> { typedef T2 type; };
template< template<class> class Selector, typename T1, typename T2 >
struct pick_max {
typedef typename pick_one< (Selector<T1>::value > Selector<T2>::value), T1, T2 >::type type;
};
template<typename T> struct size_of { static const int value = sizeof(T); };
template< size_t N, class Tuple, template<class> class Selector > struct pick_tuple_max {
typedef typename pick_tuple_max<N-1, Tuple, Selector>::type LeftMaxType;
typedef typename tbb::flow::tuple_element<N-1, Tuple>::type ThisType;
typedef typename pick_max<Selector, LeftMaxType, ThisType>::type type;
};
template< class Tuple, template<class> class Selector > struct pick_tuple_max<0, Tuple, Selector> {
typedef typename tbb::flow::tuple_element<0, Tuple>::type type;
};
// is the specified type included in a tuple?
template<class Q, size_t N, class Tuple>
struct is_element_of {
typedef typename tbb::flow::tuple_element<N-1, Tuple>::type T_i;
static const bool value = tbb::internal::is_same_type<Q,T_i>::value || is_element_of<Q,N-1,Tuple>::value;
};
template<class Q, class Tuple>
struct is_element_of<Q,0,Tuple> {
typedef typename tbb::flow::tuple_element<0, Tuple>::type T_i;
static const bool value = tbb::internal::is_same_type<Q,T_i>::value;
};
// allow the construction of types that are listed tuple. If a disallowed type
// construction is written, a method involving this type is created. The
// type has no definition, so a syntax error is generated.
template<typename T> struct ERROR_Type_Not_allowed_In_Tagged_Msg_Not_Member_Of_Tuple;
template<typename T, bool BUILD_IT> struct do_if;
template<typename T>
struct do_if<T, true> {
static void construct(void *mySpace, const T& x) {
(void) new(mySpace) Wrapper<T>(x);
}
};
template<typename T>
struct do_if<T, false> {
static void construct(void * /*mySpace*/, const T& x) {
// This method is instantiated when the type T does not match any of the
// element types in the Tuple in variant<Tuple>.
ERROR_Type_Not_allowed_In_Tagged_Msg_Not_Member_Of_Tuple<T>::bad_type(x);
}
};
// Tuple tells us the allowed types that variant can hold. It determines the alignment of the space in
// Wrapper, and how big Wrapper is.
//
// the object can only be tested for type, and a read-only reference can be fetched by cast_to<T>().
using tbb::internal::punned_cast;
struct tagged_null_type {};
template<typename TagType, typename T0, typename T1=tagged_null_type, typename T2=tagged_null_type, typename T3=tagged_null_type,
typename T4=tagged_null_type, typename T5=tagged_null_type, typename T6=tagged_null_type,
typename T7=tagged_null_type, typename T8=tagged_null_type, typename T9=tagged_null_type>
class tagged_msg {
typedef tbb::flow::tuple<T0, T1, T2, T3, T4
//TODO: Should we reject lists longer than a tuple can hold?
#if __TBB_VARIADIC_MAX >= 6
, T5
#endif
#if __TBB_VARIADIC_MAX >= 7
, T6
#endif
#if __TBB_VARIADIC_MAX >= 8
, T7
#endif
#if __TBB_VARIADIC_MAX >= 9
, T8
#endif
#if __TBB_VARIADIC_MAX >= 10
, T9
#endif
> Tuple;
private:
class variant {
static const size_t N = tbb::flow::tuple_size<Tuple>::value;
typedef typename pick_tuple_max<N, Tuple, alignment_of>::type AlignType;
typedef typename pick_tuple_max<N, Tuple, size_of>::type MaxSizeType;
static const size_t MaxNBytes = (sizeof(Wrapper<MaxSizeType>)+sizeof(AlignType)-1);
static const size_t MaxNElements = MaxNBytes/sizeof(AlignType);
typedef typename tbb::aligned_space<AlignType, MaxNElements> SpaceType;
SpaceType my_space;
static const size_t MaxSize = sizeof(SpaceType);
public:
variant() { (void) new(&my_space) Wrapper<default_constructed>(default_constructed()); }
template<typename T>
variant( const T& x ) {
do_if<T, is_element_of<T, N, Tuple>::value>::construct(&my_space,x);
}
variant(const variant& other) {
const WrapperBase * h = punned_cast<const WrapperBase *>(&(other.my_space));
h->CopyTo(&my_space);
}
// assignment must destroy and re-create the Wrapper type, as there is no way
// to create a Wrapper-to-Wrapper assign even if we find they agree in type.
void operator=( const variant& rhs ) {
if(&rhs != this) {
WrapperBase *h = punned_cast<WrapperBase *>(&my_space);
h->~WrapperBase();
const WrapperBase *ch = punned_cast<const WrapperBase *>(&(rhs.my_space));
ch->CopyTo(&my_space);
}
}
template<typename U>
const U& variant_cast_to() const {
const Wrapper<U> *h = dynamic_cast<const Wrapper<U>*>(punned_cast<const WrapperBase *>(&my_space));
if(!h) {
tbb::internal::throw_exception(tbb::internal::eid_bad_tagged_msg_cast);
}
return h->value();
}
template<typename U>
bool variant_is_a() const { return dynamic_cast<const Wrapper<U>*>(punned_cast<const WrapperBase *>(&my_space)) != NULL; }
bool variant_is_default_constructed() const {return variant_is_a<default_constructed>();}
~variant() {
WrapperBase *h = punned_cast<WrapperBase *>(&my_space);
h->~WrapperBase();
}
}; //class variant
TagType my_tag;
variant my_msg;
public:
tagged_msg(): my_tag(TagType(~0)), my_msg(){}
template<typename T, typename R>
tagged_msg(T const &index, R const &value) : my_tag(index), my_msg(value) {}
#if __TBB_CONST_REF_TO_ARRAY_TEMPLATE_PARAM_BROKEN
template<typename T, typename R, size_t N>
tagged_msg(T const &index, R (&value)[N]) : my_tag(index), my_msg(value) {}
#endif
void set_tag(TagType const &index) {my_tag = index;}
TagType tag() const {return my_tag;}
template<typename V>
const V& cast_to() const {return my_msg.template variant_cast_to<V>();}
template<typename V>
bool is_a() const {return my_msg.template variant_is_a<V>();}
bool is_default_constructed() const {return my_msg.variant_is_default_constructed();}
}; //class tagged_msg
// template to simplify cast and test for tagged_msg in template contexts
template<typename V, typename T>
const V& cast_to(T const &t) { return t.template cast_to<V>(); }
template<typename V, typename T>
bool is_a(T const &t) { return t.template is_a<V>(); }
enum op_stat { WAIT = 0, SUCCEEDED, FAILED };
} // namespace internal
#endif /* __TBB__flow_graph_types_impl_H */
+102
View File
@@ -0,0 +1,102 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_mutex_padding_H
#define __TBB_mutex_padding_H
// wrapper for padding mutexes to be alone on a cache line, without requiring they be allocated
// from a pool. Because we allow them to be defined anywhere they must be two cache lines in size.
namespace tbb {
namespace interface7 {
namespace internal {
static const size_t cache_line_size = 64;
// Pad a mutex to occupy a number of full cache lines sufficient to avoid false sharing
// with other data; space overhead is up to 2*cache_line_size-1.
template<typename Mutex, bool is_rw> class padded_mutex;
template<typename Mutex>
class padded_mutex<Mutex,false> : tbb::internal::mutex_copy_deprecated_and_disabled {
typedef long pad_type;
pad_type my_pad[((sizeof(Mutex)+cache_line_size-1)/cache_line_size+1)*cache_line_size/sizeof(pad_type)];
Mutex *impl() { return (Mutex *)((uintptr_t(this)|(cache_line_size-1))+1);}
public:
static const bool is_rw_mutex = Mutex::is_rw_mutex;
static const bool is_recursive_mutex = Mutex::is_recursive_mutex;
static const bool is_fair_mutex = Mutex::is_fair_mutex;
padded_mutex() { new(impl()) Mutex(); }
~padded_mutex() { impl()->~Mutex(); }
//! Represents acquisition of a mutex.
class scoped_lock : tbb::internal::no_copy {
typename Mutex::scoped_lock my_scoped_lock;
public:
scoped_lock() : my_scoped_lock() {}
scoped_lock( padded_mutex& m ) : my_scoped_lock(*m.impl()) { }
~scoped_lock() { }
void acquire( padded_mutex& m ) { my_scoped_lock.acquire(*m.impl()); }
bool try_acquire( padded_mutex& m ) { return my_scoped_lock.try_acquire(*m.impl()); }
void release() { my_scoped_lock.release(); }
};
};
template<typename Mutex>
class padded_mutex<Mutex,true> : tbb::internal::mutex_copy_deprecated_and_disabled {
typedef long pad_type;
pad_type my_pad[((sizeof(Mutex)+cache_line_size-1)/cache_line_size+1)*cache_line_size/sizeof(pad_type)];
Mutex *impl() { return (Mutex *)((uintptr_t(this)|(cache_line_size-1))+1);}
public:
static const bool is_rw_mutex = Mutex::is_rw_mutex;
static const bool is_recursive_mutex = Mutex::is_recursive_mutex;
static const bool is_fair_mutex = Mutex::is_fair_mutex;
padded_mutex() { new(impl()) Mutex(); }
~padded_mutex() { impl()->~Mutex(); }
//! Represents acquisition of a mutex.
class scoped_lock : tbb::internal::no_copy {
typename Mutex::scoped_lock my_scoped_lock;
public:
scoped_lock() : my_scoped_lock() {}
scoped_lock( padded_mutex& m, bool write = true ) : my_scoped_lock(*m.impl(),write) { }
~scoped_lock() { }
void acquire( padded_mutex& m, bool write = true ) { my_scoped_lock.acquire(*m.impl(),write); }
bool try_acquire( padded_mutex& m, bool write = true ) { return my_scoped_lock.try_acquire(*m.impl(),write); }
bool upgrade_to_writer() { return my_scoped_lock.upgrade_to_writer(); }
bool downgrade_to_reader() { return my_scoped_lock.downgrade_to_reader(); }
void release() { my_scoped_lock.release(); }
};
};
} // namespace internal
} // namespace interface7
} // namespace tbb
#endif /* __TBB_mutex_padding_H */
+70
View File
@@ -0,0 +1,70 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_range_iterator_H
#define __TBB_range_iterator_H
#include "../tbb_stddef.h"
#if __TBB_CPP11_STD_BEGIN_END_PRESENT && __TBB_CPP11_AUTO_PRESENT && __TBB_CPP11_DECLTYPE_PRESENT
#include <iterator>
#endif
namespace tbb {
// iterators to first and last elements of container
namespace internal {
#if __TBB_CPP11_STD_BEGIN_END_PRESENT && __TBB_CPP11_AUTO_PRESENT && __TBB_CPP11_DECLTYPE_PRESENT
using std::begin;
using std::end;
template<typename Container>
auto first(Container& c)-> decltype(begin(c)) {return begin(c);}
template<typename Container>
auto first(const Container& c)-> decltype(begin(c)) {return begin(c);}
template<typename Container>
auto last(Container& c)-> decltype(begin(c)) {return end(c);}
template<typename Container>
auto last(const Container& c)-> decltype(begin(c)) {return end(c);}
#else
template<typename Container>
typename Container::iterator first(Container& c) {return c.begin();}
template<typename Container>
typename Container::const_iterator first(const Container& c) {return c.begin();}
template<typename Container>
typename Container::iterator last(Container& c) {return c.end();}
template<typename Container>
typename Container::const_iterator last(const Container& c) {return c.end();}
#endif
template<typename T, size_t size>
T* first(T (&arr) [size]) {return arr;}
template<typename T, size_t size>
T* last(T (&arr) [size]) {return arr + size;}
} //namespace internal
} //namespace tbb
#endif // __TBB_range_iterator_H
@@ -0,0 +1,109 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// must be included outside namespaces.
#ifndef __TBB_tbb_hash_compare_impl_H
#define __TBB_tbb_hash_compare_impl_H
#include <string>
namespace tbb {
namespace interface5 {
namespace internal {
// Template class for hash compare
template<typename Key, typename Hasher, typename Key_equality>
class hash_compare
{
public:
typedef Hasher hasher;
typedef Key_equality key_equal;
hash_compare() {}
hash_compare(Hasher a_hasher) : my_hash_object(a_hasher) {}
hash_compare(Hasher a_hasher, Key_equality a_keyeq) : my_hash_object(a_hasher), my_key_compare_object(a_keyeq) {}
size_t operator()(const Key& key) const {
return ((size_t)my_hash_object(key));
}
bool operator()(const Key& key1, const Key& key2) const {
// TODO: get rid of the result invertion
return (!my_key_compare_object(key1, key2));
}
Hasher my_hash_object; // The hash object
Key_equality my_key_compare_object; // The equality comparator object
};
//! Hash multiplier
static const size_t hash_multiplier = tbb::internal::select_size_t_constant<2654435769U, 11400714819323198485ULL>::value;
} // namespace internal
//! Hasher functions
template<typename T>
inline size_t tbb_hasher( const T& t ) {
return static_cast<size_t>( t ) * internal::hash_multiplier;
}
template<typename P>
inline size_t tbb_hasher( P* ptr ) {
size_t const h = reinterpret_cast<size_t>( ptr );
return (h >> 3) ^ h;
}
template<typename E, typename S, typename A>
inline size_t tbb_hasher( const std::basic_string<E,S,A>& s ) {
size_t h = 0;
for( const E* c = s.c_str(); *c; ++c )
h = static_cast<size_t>(*c) ^ (h * internal::hash_multiplier);
return h;
}
template<typename F, typename S>
inline size_t tbb_hasher( const std::pair<F,S>& p ) {
return tbb_hasher(p.first) ^ tbb_hasher(p.second);
}
} // namespace interface5
using interface5::tbb_hasher;
// Template class for hash compare
template<typename Key>
class tbb_hash
{
public:
tbb_hash() {}
size_t operator()(const Key& key) const
{
return tbb_hasher(key);
}
};
//! hash_compare that is default argument for concurrent_hash_map
template<typename Key>
struct tbb_hash_compare {
static size_t hash( const Key& a ) { return tbb_hasher(a); }
static bool equal( const Key& a, const Key& b ) { return a == b; }
};
} // namespace tbb
#endif /* __TBB_tbb_hash_compare_impl_H */
+80
View File
@@ -0,0 +1,80 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
TBB_STRING_RESOURCE(FLOW_BROADCAST_NODE, "broadcast_node")
TBB_STRING_RESOURCE(FLOW_BUFFER_NODE, "buffer_node")
TBB_STRING_RESOURCE(FLOW_CONTINUE_NODE, "continue_node")
TBB_STRING_RESOURCE(FLOW_FUNCTION_NODE, "function_node")
TBB_STRING_RESOURCE(FLOW_JOIN_NODE_QUEUEING, "join_node (queueing)")
TBB_STRING_RESOURCE(FLOW_JOIN_NODE_RESERVING, "join_node (reserving)")
TBB_STRING_RESOURCE(FLOW_JOIN_NODE_TAG_MATCHING, "join_node (tag_matching)")
TBB_STRING_RESOURCE(FLOW_LIMITER_NODE, "limiter_node")
TBB_STRING_RESOURCE(FLOW_MULTIFUNCTION_NODE, "multifunction_node")
TBB_STRING_RESOURCE(FLOW_OR_NODE, "or_node") //no longer in use, kept for backward compatibility
TBB_STRING_RESOURCE(FLOW_OVERWRITE_NODE, "overwrite_node")
TBB_STRING_RESOURCE(FLOW_PRIORITY_QUEUE_NODE, "priority_queue_node")
TBB_STRING_RESOURCE(FLOW_QUEUE_NODE, "queue_node")
TBB_STRING_RESOURCE(FLOW_SEQUENCER_NODE, "sequencer_node")
TBB_STRING_RESOURCE(FLOW_SOURCE_NODE, "source_node")
TBB_STRING_RESOURCE(FLOW_SPLIT_NODE, "split_node")
TBB_STRING_RESOURCE(FLOW_WRITE_ONCE_NODE, "write_once_node")
TBB_STRING_RESOURCE(FLOW_BODY, "body")
TBB_STRING_RESOURCE(FLOW_GRAPH, "graph")
TBB_STRING_RESOURCE(FLOW_NODE, "node")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT, "input_port")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_0, "input_port_0")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_1, "input_port_1")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_2, "input_port_2")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_3, "input_port_3")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_4, "input_port_4")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_5, "input_port_5")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_6, "input_port_6")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_7, "input_port_7")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_8, "input_port_8")
TBB_STRING_RESOURCE(FLOW_INPUT_PORT_9, "input_port_9")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT, "output_port")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_0, "output_port_0")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_1, "output_port_1")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_2, "output_port_2")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_3, "output_port_3")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_4, "output_port_4")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_5, "output_port_5")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_6, "output_port_6")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_7, "output_port_7")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_8, "output_port_8")
TBB_STRING_RESOURCE(FLOW_OUTPUT_PORT_9, "output_port_9")
TBB_STRING_RESOURCE(FLOW_OBJECT_NAME, "object_name")
TBB_STRING_RESOURCE(FLOW_NULL, "null")
TBB_STRING_RESOURCE(FLOW_INDEXER_NODE, "indexer_node")
TBB_STRING_RESOURCE(FLOW_COMPOSITE_NODE, "composite_node")
TBB_STRING_RESOURCE(FLOW_ASYNC_NODE, "async_node")
TBB_STRING_RESOURCE(FLOW_OPENCL_NODE, "opencl_node")
TBB_STRING_RESOURCE(ALGORITHM, "tbb_algorithm")
TBB_STRING_RESOURCE(PARALLEL_FOR, "tbb_parallel_for")
TBB_STRING_RESOURCE(PARALLEL_DO, "tbb_parallel_do")
TBB_STRING_RESOURCE(PARALLEL_INVOKE, "tbb_parallel_invoke")
TBB_STRING_RESOURCE(PARALLEL_REDUCE, "tbb_parallel_reduce")
TBB_STRING_RESOURCE(PARALLEL_SCAN, "tbb_parallel_scan")
TBB_STRING_RESOURCE(PARALLEL_SORT, "tbb_parallel_sort")
TBB_STRING_RESOURCE(CUSTOM_CTX, "tbb_custom")
TBB_STRING_RESOURCE(FLOW_TASKS, "tbb_flow_graph")
TBB_STRING_RESOURCE(PARALLEL_FOR_TASK, "tbb_parallel_for_task")
// TODO: Drop following string prefix "fgt_" here and in FGA's collector
TBB_STRING_RESOURCE(USER_EVENT, "fgt_user_event")
+59
View File
@@ -0,0 +1,59 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _FGT_TBB_TRACE_IMPL_H
#define _FGT_TBB_TRACE_IMPL_H
#include "../tbb_profiling.h"
namespace tbb {
namespace internal {
#if TBB_PREVIEW_ALGORITHM_TRACE
static inline void fgt_algorithm( string_index t, void *algorithm, void *parent ) {
itt_make_task_group( ITT_DOMAIN_FLOW, algorithm, ALGORITHM, parent, ALGORITHM, t );
}
static inline void fgt_begin_algorithm( string_index t, void *algorithm ) {
itt_task_begin( ITT_DOMAIN_FLOW, algorithm, ALGORITHM, NULL, FLOW_NULL, t );
}
static inline void fgt_end_algorithm( void * ) {
itt_task_end( ITT_DOMAIN_FLOW );
}
static inline void fgt_alg_begin_body( string_index t, void *body, void *algorithm ) {
itt_task_begin( ITT_DOMAIN_FLOW, body, FLOW_BODY, algorithm, ALGORITHM, t );
}
static inline void fgt_alg_end_body( void * ) {
itt_task_end( ITT_DOMAIN_FLOW );
}
#else // TBB_PREVIEW_ALGORITHM_TRACE
static inline void fgt_algorithm( string_index /*t*/, void * /*algorithm*/, void * /*parent*/ ) { }
static inline void fgt_begin_algorithm( string_index /*t*/, void * /*algorithm*/ ) { }
static inline void fgt_end_algorithm( void * ) { }
static inline void fgt_alg_begin_body( string_index /*t*/, void * /*body*/, void * /*algorithm*/ ) { }
static inline void fgt_alg_end_body( void * ) { }
#endif // TBB_PREVIEW_ALGORITHM_TRACEE
} // namespace internal
} // namespace tbb
#endif
+73
View File
@@ -0,0 +1,73 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_tbb_windef_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif /* __TBB_tbb_windef_H */
// Check that the target Windows version has all API calls requried for TBB.
// Do not increase the version in condition beyond 0x0500 without prior discussion!
#if defined(_WIN32_WINNT) && _WIN32_WINNT<0x0501
#error TBB is unable to run on old Windows versions; _WIN32_WINNT must be 0x0501 or greater.
#endif
#if !defined(_MT)
#error TBB requires linkage with multithreaded C/C++ runtime library. \
Choose multithreaded DLL runtime in project settings, or use /MD[d] compiler switch.
#endif
// Workaround for the problem with MVSC headers failing to define namespace std
namespace std {
using ::size_t; using ::ptrdiff_t;
}
#define __TBB_STRING_AUX(x) #x
#define __TBB_STRING(x) __TBB_STRING_AUX(x)
// Default setting of TBB_USE_DEBUG
#ifdef TBB_USE_DEBUG
# if TBB_USE_DEBUG
# if !defined(_DEBUG)
# pragma message(__FILE__ "(" __TBB_STRING(__LINE__) ") : Warning: Recommend using /MDd if compiling with TBB_USE_DEBUG!=0")
# endif
# else
# if defined(_DEBUG)
# pragma message(__FILE__ "(" __TBB_STRING(__LINE__) ") : Warning: Recommend using /MD if compiling with TBB_USE_DEBUG==0")
# endif
# endif
#endif
#if (__TBB_BUILD || __TBBMALLOC_BUILD) && !defined(__TBB_NO_IMPLICIT_LINKAGE)
#define __TBB_NO_IMPLICIT_LINKAGE 1
#endif
#if _MSC_VER
#if !__TBB_NO_IMPLICIT_LINKAGE
#ifdef __TBB_LIB_NAME
#pragma comment(lib, __TBB_STRING(__TBB_LIB_NAME))
#else
#ifdef _DEBUG
#pragma comment(lib, "tbb_debug.lib")
#else
#pragma comment(lib, "tbb.lib")
#endif
#endif
#endif
#endif
+181
View File
@@ -0,0 +1,181 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_template_helpers_H
#define __TBB_template_helpers_H
#include <utility>
#include <cstddef>
namespace tbb { namespace internal {
//! Enables one or the other code branches
template<bool Condition, typename T = void> struct enable_if {};
template<typename T> struct enable_if<true, T> { typedef T type; };
//! Strips its template type argument from cv- and ref-qualifiers
template<typename T> struct strip { typedef T type; };
template<typename T> struct strip<const T> { typedef T type; };
template<typename T> struct strip<volatile T> { typedef T type; };
template<typename T> struct strip<const volatile T> { typedef T type; };
template<typename T> struct strip<T&> { typedef T type; };
template<typename T> struct strip<const T&> { typedef T type; };
template<typename T> struct strip<volatile T&> { typedef T type; };
template<typename T> struct strip<const volatile T&> { typedef T type; };
//! Specialization for function pointers
template<typename T> struct strip<T(&)()> { typedef T(*type)(); };
#if __TBB_CPP11_RVALUE_REF_PRESENT
template<typename T> struct strip<T&&> { typedef T type; };
template<typename T> struct strip<const T&&> { typedef T type; };
template<typename T> struct strip<volatile T&&> { typedef T type; };
template<typename T> struct strip<const volatile T&&> { typedef T type; };
#endif
//! Specialization for arrays converts to a corresponding pointer
template<typename T, std::size_t N> struct strip<T(&)[N]> { typedef T* type; };
template<typename T, std::size_t N> struct strip<const T(&)[N]> { typedef const T* type; };
template<typename T, std::size_t N> struct strip<volatile T(&)[N]> { typedef volatile T* type; };
template<typename T, std::size_t N> struct strip<const volatile T(&)[N]> { typedef const volatile T* type; };
//! Detects whether two given types are the same
template<class U, class V> struct is_same_type { static const bool value = false; };
template<class W> struct is_same_type<W,W> { static const bool value = true; };
template<typename T> struct is_ref { static const bool value = false; };
template<typename U> struct is_ref<U&> { static const bool value = true; };
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
//! std::void_t internal implementation (to avoid GCC < 4.7 "template aliases" absence)
template<typename...> struct void_t { typedef void type; };
#endif
#if __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
//! Allows to store a function parameter pack as a variable and later pass it to another function
template< typename... Types >
struct stored_pack;
template<>
struct stored_pack<>
{
typedef stored_pack<> pack_type;
stored_pack() {}
// Friend front-end functions
template< typename F, typename Pack > friend void call( F&& f, Pack&& p );
template< typename Ret, typename F, typename Pack > friend Ret call_and_return( F&& f, Pack&& p );
protected:
// Ideally, ref-qualified non-static methods would be used,
// but that would greatly reduce the set of compilers where it works.
template< typename Ret, typename F, typename... Preceding >
static Ret call( F&& f, const pack_type& /*pack*/, Preceding&&... params ) {
return std::forward<F>(f)( std::forward<Preceding>(params)... );
}
template< typename Ret, typename F, typename... Preceding >
static Ret call( F&& f, pack_type&& /*pack*/, Preceding&&... params ) {
return std::forward<F>(f)( std::forward<Preceding>(params)... );
}
};
template< typename T, typename... Types >
struct stored_pack<T, Types...> : stored_pack<Types...>
{
typedef stored_pack<T, Types...> pack_type;
typedef stored_pack<Types...> pack_remainder;
// Since lifetime of original values is out of control, copies should be made.
// Thus references should be stripped away from the deduced type.
typename strip<T>::type leftmost_value;
// Here rvalue references act in the same way as forwarding references,
// as long as class template parameters were deduced via forwarding references.
stored_pack( T&& t, Types&&... types )
: pack_remainder(std::forward<Types>(types)...), leftmost_value(std::forward<T>(t)) {}
// Friend front-end functions
template< typename F, typename Pack > friend void call( F&& f, Pack&& p );
template< typename Ret, typename F, typename Pack > friend Ret call_and_return( F&& f, Pack&& p );
protected:
template< typename Ret, typename F, typename... Preceding >
static Ret call( F&& f, pack_type& pack, Preceding&&... params ) {
return pack_remainder::template call<Ret>(
std::forward<F>(f), static_cast<pack_remainder&>(pack),
std::forward<Preceding>(params)... , pack.leftmost_value
);
}
template< typename Ret, typename F, typename... Preceding >
static Ret call( F&& f, const pack_type& pack, Preceding&&... params ) {
return pack_remainder::template call<Ret>(
std::forward<F>(f), static_cast<const pack_remainder&>(pack),
std::forward<Preceding>(params)... , pack.leftmost_value
);
}
template< typename Ret, typename F, typename... Preceding >
static Ret call( F&& f, pack_type&& pack, Preceding&&... params ) {
return pack_remainder::template call<Ret>(
std::forward<F>(f), static_cast<pack_remainder&&>(pack),
std::forward<Preceding>(params)... , std::move(pack.leftmost_value)
);
}
};
//! Calls the given function with arguments taken from a stored_pack
template< typename F, typename Pack >
void call( F&& f, Pack&& p ) {
strip<Pack>::type::template call<void>( std::forward<F>(f), std::forward<Pack>(p) );
}
template< typename Ret, typename F, typename Pack >
Ret call_and_return( F&& f, Pack&& p ) {
return strip<Pack>::type::template call<Ret>( std::forward<F>(f), std::forward<Pack>(p) );
}
template< typename... Types >
stored_pack<Types...> save_pack( Types&&... types ) {
return stored_pack<Types...>( std::forward<Types>(types)... );
}
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT */
#if __TBB_CPP14_INTEGER_SEQUENCE_PRESENT
using std::index_sequence;
using std::make_index_sequence;
#elif __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT && __TBB_CPP11_TEMPLATE_ALIASES_PRESENT
template<std::size_t... S> class index_sequence {};
template<std::size_t N, std::size_t... S>
struct make_index_sequence_impl : make_index_sequence_impl < N - 1, N - 1, S... > {};
template<std::size_t... S>
struct make_index_sequence_impl <0, S...> {
using type = index_sequence<S...>;
};
template<std::size_t N>
using make_index_sequence = typename tbb::internal::make_index_sequence_impl<N>::type;
#endif /* __TBB_CPP14_INTEGER_SEQUENCE_PRESENT */
} } // namespace internal, namespace tbb
#endif /* __TBB_template_helpers_H */
@@ -0,0 +1,148 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__x86_eliding_mutex_impl_H
#define __TBB__x86_eliding_mutex_impl_H
#ifndef __TBB_spin_mutex_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#if ( __TBB_x86_32 || __TBB_x86_64 )
namespace tbb {
namespace interface7 {
namespace internal {
template<typename Mutex, bool is_rw>
class padded_mutex;
//! An eliding lock that occupies a single byte.
/** A x86_eliding_mutex is an HLE-enabled spin mutex. It is recommended to
put the mutex on a cache line that is not shared by the data it protects.
It should be used for locking short critical sections where the lock is
contended but the data it protects are not. If zero-initialized, the
mutex is considered unheld.
@ingroup synchronization */
class x86_eliding_mutex : tbb::internal::mutex_copy_deprecated_and_disabled {
//! 0 if lock is released, 1 if lock is acquired.
__TBB_atomic_flag flag;
friend class padded_mutex<x86_eliding_mutex, false>;
public:
//! Construct unacquired lock.
/** Equivalent to zero-initialization of *this. */
x86_eliding_mutex() : flag(0) {}
// bug in gcc 3.x.x causes syntax error in spite of the friend declaration above.
// Make the scoped_lock public in that case.
#if __TBB_USE_X86_ELIDING_MUTEX || __TBB_GCC_VERSION < 40000
#else
// by default we will not provide the scoped_lock interface. The user
// should use the padded version of the mutex. scoped_lock is used in
// padded_mutex template.
private:
#endif
// scoped_lock in padded_mutex<> is the interface to use.
//! Represents acquisition of a mutex.
class scoped_lock : tbb::internal::no_copy {
private:
//! Points to currently held mutex, or NULL if no lock is held.
x86_eliding_mutex* my_mutex;
public:
//! Construct without acquiring a mutex.
scoped_lock() : my_mutex(NULL) {}
//! Construct and acquire lock on a mutex.
scoped_lock( x86_eliding_mutex& m ) : my_mutex(NULL) { acquire(m); }
//! Acquire lock.
void acquire( x86_eliding_mutex& m ) {
__TBB_ASSERT( !my_mutex, "already holding a lock" );
my_mutex=&m;
my_mutex->lock();
}
//! Try acquiring lock (non-blocking)
/** Return true if lock acquired; false otherwise. */
bool try_acquire( x86_eliding_mutex& m ) {
__TBB_ASSERT( !my_mutex, "already holding a lock" );
bool result = m.try_lock();
if( result ) {
my_mutex = &m;
}
return result;
}
//! Release lock
void release() {
__TBB_ASSERT( my_mutex, "release on scoped_lock that is not holding a lock" );
my_mutex->unlock();
my_mutex = NULL;
}
//! Destroy lock. If holding a lock, releases the lock first.
~scoped_lock() {
if( my_mutex ) {
release();
}
}
};
#if __TBB_USE_X86_ELIDING_MUTEX || __TBB_GCC_VERSION < 40000
#else
public:
#endif /* __TBB_USE_X86_ELIDING_MUTEX */
// Mutex traits
static const bool is_rw_mutex = false;
static const bool is_recursive_mutex = false;
static const bool is_fair_mutex = false;
// ISO C++0x compatibility methods
//! Acquire lock
void lock() {
__TBB_LockByteElided(flag);
}
//! Try acquiring lock (non-blocking)
/** Return true if lock acquired; false otherwise. */
bool try_lock() {
return __TBB_TryLockByteElided(flag);
}
//! Release lock
void unlock() {
__TBB_UnlockByteElided( flag );
}
}; // end of x86_eliding_mutex
} // namespace internal
} // namespace interface7
} // namespace tbb
#endif /* ( __TBB_x86_32 || __TBB_x86_64 ) */
#endif /* __TBB__x86_eliding_mutex_impl_H */
@@ -0,0 +1,225 @@
/*
Copyright (c) 2005-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB__x86_rtm_rw_mutex_impl_H
#define __TBB__x86_rtm_rw_mutex_impl_H
#ifndef __TBB_spin_rw_mutex_H
#error Do not #include this internal file directly; use public TBB headers instead.
#endif
#if __TBB_TSX_AVAILABLE
#include "../tbb_stddef.h"
#include "../tbb_machine.h"
#include "../tbb_profiling.h"
#include "../spin_rw_mutex.h"
namespace tbb {
namespace interface8 {
namespace internal {
enum RTM_type {
RTM_not_in_mutex,
RTM_transacting_reader,
RTM_transacting_writer,
RTM_real_reader,
RTM_real_writer
};
static const unsigned long speculation_granularity = 64;
//! Fast, unfair, spinning speculation-enabled reader-writer lock with backoff and
// writer-preference
/** @ingroup synchronization */
class x86_rtm_rw_mutex: private spin_rw_mutex {
#if __TBB_USE_X86_RTM_RW_MUTEX || __TBB_GCC_VERSION < 40000
// bug in gcc 3.x.x causes syntax error in spite of the friend declaration below.
// Make the scoped_lock public in that case.
public:
#else
private:
#endif
friend class interface7::internal::padded_mutex<x86_rtm_rw_mutex,true>;
class scoped_lock; // should be private
friend class scoped_lock;
private:
//! @cond INTERNAL
//! Internal construct unacquired mutex.
void __TBB_EXPORTED_METHOD internal_construct();
//! Internal acquire write lock.
// only_speculate == true if we're doing a try_lock, else false.
void __TBB_EXPORTED_METHOD internal_acquire_writer(x86_rtm_rw_mutex::scoped_lock&, bool only_speculate=false);
//! Internal acquire read lock.
// only_speculate == true if we're doing a try_lock, else false.
void __TBB_EXPORTED_METHOD internal_acquire_reader(x86_rtm_rw_mutex::scoped_lock&, bool only_speculate=false);
//! Internal upgrade reader to become a writer.
bool __TBB_EXPORTED_METHOD internal_upgrade( x86_rtm_rw_mutex::scoped_lock& );
//! Out of line code for downgrading a writer to a reader.
bool __TBB_EXPORTED_METHOD internal_downgrade( x86_rtm_rw_mutex::scoped_lock& );
//! Internal try_acquire write lock.
bool __TBB_EXPORTED_METHOD internal_try_acquire_writer( x86_rtm_rw_mutex::scoped_lock& );
//! Internal release lock.
void __TBB_EXPORTED_METHOD internal_release( x86_rtm_rw_mutex::scoped_lock& );
static x86_rtm_rw_mutex* internal_get_mutex( const spin_rw_mutex::scoped_lock& lock )
{
return static_cast<x86_rtm_rw_mutex*>( lock.internal_get_mutex() );
}
static void internal_set_mutex( spin_rw_mutex::scoped_lock& lock, spin_rw_mutex* mtx )
{
lock.internal_set_mutex( mtx );
}
//! @endcond
public:
//! Construct unacquired mutex.
x86_rtm_rw_mutex() {
w_flag = false;
#if TBB_USE_THREADING_TOOLS
internal_construct();
#endif
}
#if TBB_USE_ASSERT
//! Empty destructor.
~x86_rtm_rw_mutex() {}
#endif /* TBB_USE_ASSERT */
// Mutex traits
static const bool is_rw_mutex = true;
static const bool is_recursive_mutex = false;
static const bool is_fair_mutex = false;
#if __TBB_USE_X86_RTM_RW_MUTEX || __TBB_GCC_VERSION < 40000
#else
// by default we will not provide the scoped_lock interface. The user
// should use the padded version of the mutex. scoped_lock is used in
// padded_mutex template.
private:
#endif
//! The scoped locking pattern
/** It helps to avoid the common problem of forgetting to release lock.
It also nicely provides the "node" for queuing locks. */
// Speculation-enabled scoped lock for spin_rw_mutex
// The idea is to be able to reuse the acquire/release methods of spin_rw_mutex
// and its scoped lock wherever possible. The only way to use a speculative lock is to use
// a scoped_lock. (because transaction_state must be local)
class scoped_lock : tbb::internal::no_copy {
friend class x86_rtm_rw_mutex;
spin_rw_mutex::scoped_lock my_scoped_lock;
RTM_type transaction_state;
public:
//! Construct lock that has not acquired a mutex.
/** Equivalent to zero-initialization of *this. */
scoped_lock() : my_scoped_lock(), transaction_state(RTM_not_in_mutex) {
}
//! Acquire lock on given mutex.
scoped_lock( x86_rtm_rw_mutex& m, bool write = true ) : my_scoped_lock(),
transaction_state(RTM_not_in_mutex) {
acquire(m, write);
}
//! Release lock (if lock is held).
~scoped_lock() {
if(transaction_state != RTM_not_in_mutex) release();
}
//! Acquire lock on given mutex.
void acquire( x86_rtm_rw_mutex& m, bool write = true ) {
if( write ) m.internal_acquire_writer(*this);
else m.internal_acquire_reader(*this);
}
//! Release lock
void release() {
x86_rtm_rw_mutex* mutex = x86_rtm_rw_mutex::internal_get_mutex(my_scoped_lock);
__TBB_ASSERT( mutex, "lock is not acquired" );
__TBB_ASSERT( transaction_state!=RTM_not_in_mutex, "lock is not acquired" );
return mutex->internal_release(*this);
}
//! Upgrade reader to become a writer.
/** Returns whether the upgrade happened without releasing and re-acquiring the lock */
bool upgrade_to_writer() {
x86_rtm_rw_mutex* mutex = x86_rtm_rw_mutex::internal_get_mutex(my_scoped_lock);
__TBB_ASSERT( mutex, "lock is not acquired" );
__TBB_ASSERT( transaction_state==RTM_transacting_reader || transaction_state==RTM_real_reader, "Invalid state for upgrade" );
return mutex->internal_upgrade(*this);
}
//! Downgrade writer to become a reader.
/** Returns whether the downgrade happened without releasing and re-acquiring the lock */
bool downgrade_to_reader() {
x86_rtm_rw_mutex* mutex = x86_rtm_rw_mutex::internal_get_mutex(my_scoped_lock);
__TBB_ASSERT( mutex, "lock is not acquired" );
__TBB_ASSERT( transaction_state==RTM_transacting_writer || transaction_state==RTM_real_writer, "Invalid state for downgrade" );
return mutex->internal_downgrade(*this);
}
//! Attempt to acquire mutex.
/** returns true if successful. */
bool try_acquire( x86_rtm_rw_mutex& m, bool write = true ) {
#if TBB_USE_ASSERT
x86_rtm_rw_mutex* mutex = x86_rtm_rw_mutex::internal_get_mutex(my_scoped_lock);
__TBB_ASSERT( !mutex, "lock is already acquired" );
#endif
// have to assign m to our mutex.
// cannot set the mutex, because try_acquire in spin_rw_mutex depends on it being NULL.
if(write) return m.internal_try_acquire_writer(*this);
// speculatively acquire the lock. If this fails, do try_acquire on the spin_rw_mutex.
m.internal_acquire_reader(*this, /*only_speculate=*/true);
if(transaction_state == RTM_transacting_reader) return true;
if( my_scoped_lock.try_acquire(m, false)) {
transaction_state = RTM_real_reader;
return true;
}
return false;
}
}; // class x86_rtm_rw_mutex::scoped_lock
// ISO C++0x compatibility methods not provided because we cannot maintain
// state about whether a thread is in a transaction.
private:
char pad[speculation_granularity-sizeof(spin_rw_mutex)]; // padding
// If true, writer holds the spin_rw_mutex.
tbb::atomic<bool> w_flag; // want this on a separate cache line
}; // x86_rtm_rw_mutex
} // namespace internal
} // namespace interface8
} // namespace tbb
#endif /* __TBB_TSX_AVAILABLE */
#endif /* __TBB__x86_rtm_rw_mutex_impl_H */