Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 35

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 35 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 352018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 35)

It then calls RunL() on the specified activeobject.• When the call to RunL() has completed, the active schedulerissues another call to User::WaitForAnyRequest() and waitsfor the next event to occur. This implies that the scheduler handles precisely one event per User::WaitForAnyRequest(). Ifmore than one event is outstanding, there’s no problem; the nextUser::WaitForAnyRequest() completes immediately withoutsuspending the thread and the scheduler finds the active objectassociated with the completed event by applying the same criteria.Given this description, you might expect writing an active object to bedifficult. In fact, as we’ve already seen with CDelayedHello, it is not.You simply have to:• issue request functions to an asynchronous service provider, remembering to call SetActive() after you have done so• handle completed requests with RunL()• cancel requests with DoCancel()• set an appropriate priority• handle leaving from RunL() with RunError().6.5 Active Object PrioritiesAs we have now seen, the active-scheduler framework provides non-preemptive multitasking within the context of a single thread.

Whilst one172ACTIVE OBJECTSRunL() call is being processed, no other RunL() call within the samethread can execute or be pre-empted. This means that it is important tounderstand the importance of choosing priorities for active objects.If the thread’s request semaphore is signaled more than once (i.e. twoor more events occur simultaneously), before the active scheduler candispatch an active object’s RunL(), it has to decide which active objectto service first. The queue of active objects is ordered by the priority ofthose objects, with the highest-priority object at the head of the queue.The active scheduler always starts looking for an active object to run atthe head of the queue, working through the queue until it finds an objectthat satisfies the criteria we described in Section 6.4.For this reason, if two objects are ready to run, one with a low priorityand another with a high priority, the active scheduler calls RunL() onthe higher priority object first.

If two active objects with the same priorityare both ready to run, then the object which was added to the activescheduler first, via CActiveScheduler::Add(), is the first object tohave its RunL() method called.The scheduler does not use a round-robin algorithm. If two or moreactive objects with the same priority are ready to run, the offer to runalways goes to the one that is higher in the scheduler’s queue.The CActive class defines a basic set of priority values, encapsulatedby the TPriority enumeration:// Defines standard priorities for active objects.enum TPriority{// A low priority, useful for active objects representing// background processing.EPriorityIdle =-100,// A priority higher than EPriorityIdle but lower than// EPriorityStandard.EPriorityLow = -20,// Most active objects will have this priority.EPriorityStandard = 0,// A priority higher than EPriorityStandard; useful for// active objects handling user input.EPriorityUserInput = 10,// A priority higher than EPriorityUserInput.EPriorityHigh = 20};The application framework (CONE) defines an additional set of priorities, TActivePriority, in coemain.h:ACTIVE OBJECT PRIORITIES173// UI Control framework active object priorities.// These are in addition to the values contained in the// TPriority enum in class CActive.enum TActivePriority{// 300EActivePriorityClockTimer=300,// 200EActivePriorityIpcEventsHigh=200,// 150EActivePriorityFepLoader=150,// 100EActivePriorityWsEvents=100,// 50EActivePriorityRedrawEvents=50,// 0EActivePriorityDefault=0,// 10EActivePriorityLogonA=-10};Most applications use CActive::EPriorityStandard as theirstandard priority value, but if you need to use non-zero values for yourown active objects, then you need to look at the enumeration values sothat you can ensure you fit in with them.Since a RunL() dispatch cannot be pre-empted by any other activeobject in the same scheduler, this means that it is possible for oneslow, low-priority, active object RunL() to delay the RunL() of ahigher-priority object.

For example, the Control Environment installs ahigh-priority active object to receive key, pen and other kinds of eventsfrom the Window Server. This object needs to have a high priority toensure that it runs as soon as possible after an event occurs, so asto maintain a high degree of responsiveness. However, if the activescheduler contains an object that takes a long time to finish its RunL()processing, then the user’s key or pen input cannot be processed untilthat slow RunL() completes. For this reason, its important to ensure thatRunL() calls complete quickly, no matter where they are within thescheduler’s queue.Having the wrong priority for your active object can also lead to activeobject starvation.

If an object that receives a large number of events isalways in a ready-to-run state because its request has been completed,then if its priority is very high it may prevent other ready-to-run objectslower down the priority list from being dispatched. This is a commonproblem when using timer active objects, or CIdle, if their prioritiesare too high.

In e32base.h, the CIdle class provides a ready-madewrapper for idle-time processing. It is an active object that ‘calls back’a function when no other active object is ready to run. The idle objectcompletes its own request status immediately when it is started, so thatit is always ready to run. You should generally create a CIdle object174ACTIVE OBJECTSwith a priority of CActive::EPriorityIdle, which ensures that theobject appears near the end of the scheduler queue. When no higherpriority object is ready to run, the idle-time processing function is called.However, if you give the idle object a higher priority, it may end uprunning ahead of other active objects, preventing them from having theirRunL() functions called.If you find that your RunL() is not being called when you think itshould be, check the priority of your object and think about the priorityof other objects within your scheduler.

It is possible that the object’spriority is too low or that some other object’s priority is too high.Even though the priority of an active object is defined during itsconstruction, it is possible to adjust the priority afterwards, providing theobject is not active. The CActive base class provides a SetPriority()method which can be used to adjust the priority after it has been addedto the scheduler. Whilst its use is fairly uncommon, it can be used as ameans of counteracting the event starvation problem, essentially creatinga manual round-robin scheduling algorithm.In Symbian OS communications programming, it is common for oneactive object to handle outgoing data transfer and another active objectto handle incoming data.

In this situation, it can be dangerous to giveone object a fixed higher priority than the other, since it may mean that aflood of incoming data prevents the outgoing data-transfer active objectfrom having a chance to run. Generally, it is desirable to have the objectsclose to one another in priority, but you may still need to take furtheraction to ensure that both objects have an equal chance of having theirRunL() methods called.In Figure 6.5, both objects have the same priority of zero but we knowthat the order in which the RunL() functions for these objects are calledis based upon the order in which they were added to the scheduler.

Inthe case where both are ready to handle an event, one or other objectalways runs before the other, which may lead to event starvation. In thisFigure 6.5Active objects in a communications programACTIVE OBJECT PRIORITIES175example, the reader (RX) object was added to the scheduler before thewriter (TX) object and therefore, if both are ready to run, the RunL()method of the reader object is always called first.

If the reader is receivinga large amount of data, but an important outgoing transmission packetneeds to be sent, then the sending of the outgoing packet does not occuruntil the reader object is no longer ready to run.One way to counteract this problem is to have one object adjust itspriority when its RunL() method is called, so that it pivots around acentral priority point (see Figure 6.6). For example, the reader objectcould alternate between the priority values of zero and minus one. Thefirst time RunL() is called, the object adjusts its priority by callingSetPriority(-1).Figure 6.6Active objects with dynamic reader-priority adjustmentIn this way, even though the reader is still ready to run almostimmediately, the RunL() method of the writer is now called first and itcan send that critical packet. The next time the reader’s RunL() methodis called, it toggles its priority back to zero.A simpler alternative to priority toggling is to keep both objects atthe same priority, but adjust the position in which they appear relativeto other objects of the same priority in the active scheduler’s queue.When the object’s RunL() is called, the object removes itself fromthe active scheduler, by calling CActive::Deque() and then callsCActiveScheduler::Add() again.

Характеристики

Тип файла
PDF-файл
Размер
6,45 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6420
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее