quick_recipes (779892), страница 13

Файл №779892 quick_recipes (Symbian Books) 13 страницаquick_recipes (779892) страница 132018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The events are generated by asynchronousservices encapsulated in active objects, each with an event-handlingfunction that the active scheduler calls if the request associated with theactive object completes.1 So, when the asynchronous service associatedwith an active object completes, it generates an event, which is detectedby the active scheduler. The active scheduler determines which activeobject is associated with the event, and calls the appropriate active objectto handle the event.Tip: An active object encapsulates a task; it requests an asynchronousservice from a service provider and handles the completion event laterwhen the active scheduler calls it.Within a single application thread, active objects run independently ofeach other, similar to the way that threads are independent of each otherin a process.

A switch between active objects in a single thread incurs alower overhead than a thread context switch, described shortly, which isideal for lightweight event-driven multitasking on Symbian OS.3.15.1 PreemptionWithin a single thread, the active object framework uses non-preemptivemultitasking. Once invoked, an event handler must run to completionbefore any other active object’s event handler can run – it cannot bepreempted.Some events strictly require a response within a guaranteed time,regardless of any other activity in the system (e.g., low-level telephony).This is called ‘real-time’ event handling. Active objects are not suitable forreal-time tasks and on Symbian OS real-time tasks should be implementedusing high-priority threads.

Symbian OS threads are scheduled preemptively by the kernel, which runs the highest-priority thread eligible. The1Windows programmers may recognize the pattern of message loop and messagedispatch which drives a Win32 application. The active scheduler takes the place of theWindows message loop and the event-handling function of an active object acts as themessage handler.ACTIVE OBJECTS67kernel controls thread scheduling, allowing the threads to share systemresources by time-slice division, preempting the running of a thread ifanother, higher-priority thread becomes eligible to run.A context switch occurs when the current thread is suspended (forexample, if it becomes blocked, has reached the end of its time-slice,or a higher-priority thread becomes ready to run) and another threadis made current by the kernel scheduler.

The context switch incurs aruntime overhead in terms of the kernel scheduler and, if the originaland replacing threads are executing in different processes, the memorymanagement unit and hardware caches.3.15.2 Class CActiveAn active object class must derive directly or indirectly from classCActive, defined in e32base.h.

CActive is an abstract class withtwo pure virtual functions, RunL() and DoCancel().ConstructionOn construction, classes deriving from CActive must call the protectedconstructor of the base class, passing in a parameter to set the priority ofthe active object. Like threads, all active objects have a priority value todetermine how they are scheduled. As the previous subsection described,once an active object is handling an event, it cannot be preempted untilthe event-handler function has returned back to the active scheduler.During this time, a number of completion events may occur. When theactive scheduler next gets to run, it must resolve which active object getsto run next.

It would not be desirable for a low-priority active object tohandle its event if a higher-priority active object was also waiting, soevents are handled sequentially in order of the highest priority rather thanin order of completion.In its constructor, the active object should also add itself to the activescheduler by calling CActiveScheduler::Add().Making a request and handling its completion in RunL()Figure 3.3 illustrates the basic sequence of actions performed when anactive object submits a request to an asynchronous service provider.

Anactive object class supplies public methods that submit such a request,for which the standard behavior is as follows.1. Check for outstanding requests.An active object must never have more than one outstanding request,so before attempting to submit a request, the active object must checkto see if it is already waiting on completion.68SYMBIAN OS DEVELOPMENT BASICSActive Object(1) Issues requestpassing iStatusAsynchronous ServiceProvider(2) Sets iStatus=KRequestPending andstarts the asynchronous service(3) Calls SetActive()on itself(5) Active Scheduler callsRunL() on the active objectto handle the event(4) Service completes.Service provider usesRequestComplete() to notify theActive Scheduler and post acompletion resultRunL() resubmits anotherrequest or stops the ActiveSchedulerRunL() cannot be preemptedFigure 3.3PROCESS ORTHREADBOUNDARYA Request to an Asynchronous Service Provider, which Generates an Event on Completion2.Submit the request.The active object submits a request to the service provider, passingin the TRequestStatus member variable (iStatus).

The serviceprovider must set this value to KRequestPending before initiatingthe asynchronous request.3.Call SetActive() to mark the object as ‘waiting’.A call to CActive::SetActive() indicates that a request hasbeen submitted and is currently outstanding. This call should not bemade until after the request has been submitted.Each active object class must implement the pure virtual RunL()method inherited from the CActive base class.

This is the event handler method called by the active scheduler when a completion eventoccurs.ACTIVE OBJECTS69RunL() should check whether the asynchronous request succeededby inspecting its completion code, which is the 32-bit integer value storein the TRequestStatus object (iStatus) of the active object. Thecomplexity of RunL() code can vary considerably, but since RunL()cannot be preempted by other active objects’ event handlers while it isrunning, it should complete as quickly as possible so that other eventscan be handled without delay.DoCancel()An active object must be able to cancel an outstanding asynchronousrequest. An active object class must implement the pure virtual DoCancel() method of the base class to terminate a request by calling theappropriate cancellation method on the asynchronous service provider.DoCancel() must not leave or allocate resources and should not carryout any lengthy operations, but simply cancel the request and performany associated cleanup.CActive::Cancel() calls DoCancel() and waits for notificationthat the request has terminated.

Cancel() must be called whenever arequest is to be terminated, not DoCancel(), since the base class methodchecks whether a request is outstanding and performs the necessary waituntil it has terminated.RunError()The CActive base class provides a virtual RunError() method whichthe active scheduler calls if RunL() leaves. If the leave can be handled, this should be done by overriding the default implementation ofCActive::RunError() to handle the exception.DestructionThe destructor of a CActive-derived class should always call Cancel()to cancel any outstanding requests.

The CActive base-class destructorchecks that the active object is not currently active. It panics withE32USER – CBASE 40 if any request is outstanding; that is, if Cancel()has not been called. This catches any programming errors where a callto Cancel() has been forgotten. Having verified that the active objecthas no issued requests outstanding, the CActive destructor removes theactive object from the active scheduler.The reason it is so important to cancel requests before destroying anactive object is that otherwise the request would complete after the activeobject had been destroyed. This would cause a ‘stray signal’ because theactive scheduler is unable to find a handler for the event. This results ina panic (E32USER – CBASE 46).70SYMBIAN OS DEVELOPMENT BASICS3.15.3 Class TRequestStatusOne of the most ubiquitous classes of Symbian OS is TRequestStatus.It is used for all kinds of purposes: synchronization, multithreading,multiprocessing, system interaction and asynchronous calls.A TRequestStatus object is basically a thread-specific rendezvousobject.

One Symbian OS thread can wait for another using User::WaitForRequest(), passing in a TRequestStatus object. Likewise, onethread can notify another using User::RequestComplete().Each thread can only wait on one TRequestStatus at any time. Theexception to this rule is User::WaitForAnyRequest(), which makesthe thread wait for any completion event.Each Symbian OS thread keeps track of how many of its requests werecompleted, so that if it waits on one request (A) while another request (B)is completed, the completion information is retained and the next call toUser::WaitForRequest(B) will return immediately.Each TRequestStatus also contains an integer instance variable,which is set to KRequestPending just before calling User::WaitForRequest(), either directly or through a call to an API that calls anasynchronous method, such as those provided by Symbian OS.When a request is completed, the instance variable allows someinter-thread information transfer, usually an error code or KErrNone.3.15.4 The Active SchedulerMost threads running on Symbian OS have an active scheduler, which isusually created and started implicitly by a framework (for example, CONEfor the GUI framework).

There is only one active scheduler created perthread, although it can be nested in advanced cases.Console-based test code must create an active scheduler in its mainthread if it depends on components which use active objects. The codeto do this is as follows:CActiveScheduler* scheduler = new(ELeave) CActiveScheduler;CleanupStack::PushL(scheduler);CActiveScheduler::Install(scheduler);Once the active scheduler has been created and installed, its eventprocessing wait loop must be started by calling CActiveScheduler::Start(). The event-processing loop starts and does not return untila call is made to CActiveScheduler::Stop().

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

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

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

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