![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
CustomizationBoost , Chapter 1. Fiber , Chapter 1. Fiber
|
| |
Предоставьте методы доступа к чтению по своему усмотрению. | |
Важно позвонить | |
Свойство, которое не влияет на планировщик, не нуждается в методах доступа. |
Теперь мы можем вывести пользовательский планировщик из algorithm_with_properties<>
, указав в качестве параметра шаблона наш пользовательский класс свойств priority_props
.
class priority_scheduler : public boost::fibers::algo::algorithm_with_properties< priority_props > { private: typedef boost::fibers::scheduler::ready_queue_trqueue_t; rqueue_t rqueue_; std::mutex mtx_{}; std::condition_variable cnd_{}; bool flag_{ false }; public: priority_scheduler() : rqueue_() { } // For a subclass of algorithm_with_properties<>, it's important to // override the correct awakened() overload.
virtual void awakened( boost::fibers::context * ctx, priority_props & props) noexcept { int ctx_priority = props.get_priority();
// With this scheduler, fibers with higher priority values are // preferred over fibers with lower priority values. But fibers with // equal priority values are processed in round-robin fashion. So when // we're handed a new context*, put it at the end of the fibers // with that same priority. In other words: search for the first fiber // in the queue with LOWER priority, and insert before that one. rqueue_t::iterator i( std::find_if( rqueue_.begin(), rqueue_.end(), [ctx_priority,this]( boost::fibers::context & c) { return properties( &c ).get_priority() < ctx_priority; })); // Now, whether or not we found a fiber with lower priority, // insert this new fiber here. rqueue_.insert( i, * ctx); }
virtual boost::fibers::context * pick_next() noexcept { // if ready queue is empty, just tell caller if ( rqueue_.empty() ) { return nullptr; } boost::fibers::context * ctx( & rqueue_.front() ); rqueue_.pop_front(); return ctx; }
virtual bool has_ready_fibers() const noexcept { return ! rqueue_.empty(); }
virtual void property_change( boost::fibers::context * ctx, priority_props & props) noexcept { // Although our priority_props class defines multiple properties, only // one of them (priority) actually calls notify() when changed. The // point of a property_change() override is to reshuffle the ready // queue according to the updated priority value. // 'ctx' might not be in our queue at all, if caller is changing the // priority of (say) the running fiber. If it's not there, no need to // move it: we'll handle it next time it hits awakened(). if ( ! ctx->ready_is_linked()) {
return; } // Found ctx: unlink it ctx->ready_unlink(); // Here we know that ctx was in our ready queue, but we've unlinked // it. We happen to have a method that will (re-)add a context* to the // right place in the ready queue. awakened( ctx, props); } void suspend_until( std::chrono::steady_clock::time_point const& time_point) noexcept { if ( (std::chrono::steady_clock::time_point::max)() == time_point) { std::unique_lock< std::mutex > lk( mtx_); cnd_.wait( lk, [this](){ return flag_; }); flag_ = false; } else { std::unique_lock< std::mutex > lk( mtx_); cnd_.wait_until( lk, time_point, [this](){ return flag_; }); flag_ = false; } } void notify() noexcept { std::unique_lock< std::mutex > lk( mtx_); flag_ = true; lk.unlock(); cnd_.notify_all(); } };
См. ready_queue_t. | |
Вы должны переопределить метод | |
| |
Вы должны переопределить метод | |
Вы должны переопределить | |
Переопределение | |
Ваш |
algorithm_with_properties::new_properties()
:
priority_props
экземпляры на кучи.
.
Вы должны позвонить use_scheduling_algorithm()
в начале каждого потока, на котором вы хотите Boost.Fiber использовать свой собственный планировщик, а не свой собственный по умолчанию round_robin
. В частности, вы должны позвонить use_scheduling_algorithm()
, прежде чем выполнять какие-либо другие операции Boost.Fiber.
int main( int argc, char *argv[]) { // make sure we use our priority_scheduler rather than default round_robin boost::fibers::use_scheduling_algorithm< priority_scheduler >(); ... }
Работающее волокно может получить доступ к своему собственному экземпляру подкласса fiber_properties
, позвонив this_fiber::properties()
.Хотя properties<>()
является нулевой функцией, вы должны пройти, как параметр шаблона, подкласс fiber_properties
.
boost::this_fiber::properties< priority_props >().name = "main";
Учитывая экземпляр волокно
, все еще связанный с работающим волокном (то есть не волокно::detach()
ed), вы можете получить доступ к свойствам этого волокна, используя волокно::свойства()
. Как и в случае с this_fiber::свойства<>()
, вы должны пройти подкласс fiber_свойства
в качестве параметра шаблона.
template< typename Fn > boost::fibers::fiber launch( Fn && func, std::string const& name, int priority) { boost::fibers::fiber fiber( func); priority_props & props( fiber.properties< priority_props >() ); props.name = name; props.set_priority( priority); return fiber; }
Запуск новых волоконных графиков, которые клетчатки готовы, но не сразу же вводят свою волокно-функцию. Токовое волокно сохраняет контроль до тех пор, пока не блокирует (или не дает, или не прекращает) по какой-либо другой причине. Как показано в описанной выше функции launch()
, разумно запустить волокно и сразу же установить соответствующие свойства, такие как, например, его приоритет. Затем ваш пользовательский планировщик может использовать эту информацию в следующий раз, когда менеджер волокон позвонит algorithm_with_properties::pick_next()
.
[9] Предыдущая версия библиотеки Fiber неявно отслеживала внутренний приоритет для каждого волокна, хотя планировщик по умолчанию проигнорировал его. Это было отброшено, так как библиотека теперь поддерживает произвольные свойства календаря.
Статья Customization раздела Chapter 1. Fiber Chapter 1. Fiber может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.
:: Главная :: Chapter 1. Fiber ::
реклама |