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

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

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

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

The statemachine then moves itself into the Show InfoHello state. Here amessage is produced showing the greeting text. Again the state machinemoves itself into the Wait State where it starts a timer. When the timercompletes, it notifies the state machine, moves to Show Hello and thecycle repeats. Canceling the state machine can be done in any state andsimply moves the state machine into the Idle state.This is a very simple state machine but it demonstrates the idea.

TheCMultiPartHello object implements the state machine. It is an activeobject that maintains an outstanding request, once it has been started,until it is cancelled.class CMultiPartHello : public CActive{public:static CMultiPartHello* NewL(CActiveHelloAppView* aAppView);∼CMultiPartHello();void Start(TTimeIntervalMicroSeconds32 aDelay);private: // From CActivevoid RunL();void DoCancel();TInt RunError(TInt aError);private:CMultiPartHello();void ConstructL(CActiveHelloAppView* aAppView);void CompleteSelf();192ACTIVE OBJECTSvoid ShowText(TBool aShowText);private: // Enumsenum THelloState{EIdle= 0,EShowHello,EHideHello,EShowInfoHello,EWaitState};private:RTimer iTimer;TTimeIntervalMicroSeconds32 iDelay;THelloState iState;CEikonEnv* iEnv;CActiveHelloAppView* iAppView;};The CompleteSelf() function makes the active object eligible forRunL() next time control is returned to the active scheduler.void CMultiPartHello::CompleteSelf(){TRequestStatus* pStat = &iStatus;User::RequestComplete(pStat, KErrNone);SetActive();}The User::RequestComplete() function results in three actions:• iStatus is set to KRequestPending, which ensures that theTRequestStatus flags are correctly updated in accordance withactive object and active scheduler protocols• the request status is changed from KRequestPending to the suppliedcompletion status code, in this case, KErrNone• RThread::RequestComplete() is called, resulting in a kernelexecutive call which ultimately increments the thread’s requestsemaphore by one.The object then sets itself active.

The net effect is to make it appear asif the active object issued a request that has been completed. Thereforethe active scheduler can call RunL().RunL() implements the behavior for the different states.void CMultiPartHello::RunL(){THelloState nextState = iState;switch (iState){IMPLEMENTING STATE MACHINES193case EShowHello:{ShowText(ETrue);// issue requestiTimer.After(iStatus, iDelay);SetActive();nextState = EHideHello;break;}case EHideHello:{ShowText(EFalse);CompleteSelf();nextState = EShowInfoHello;break;}case EShowInfoHello:{iEnv->InfoMsg(R_ACTIVEHELLO_TEXT_HELLO);CompleteSelf();nextState = EWaitState;break;}case EWaitState:{// issue requestiTimer.After(iStatus, iDelay);SetActive();nextState = EShowHello;break;}default:break;}iState = nextState;}When RunL() is entered, the switch statement performs the desiredbehavior and the next state is set.

The next state is performed whenRunL() is next called. This can be due to either an asynchronous requestbeing completed (the timer in this example) or by the state machinecompleting itself.You could argue that there is no need for the CompleteSelf() functionality – the states can be amalgamated. Applying this to our examplewould mean that Hide Hello, Show InfoHello and Wait Statecould be amalgamated into a single state. So why not do this? One reasonwould be to allow control to be returned to the active scheduler andtherefore maintain responsiveness, that is, to allow higher-priority activeobjects, such as the Control Environment’s user input handler, to be givensome processor time.

Also, state machines are not usually as simple asthis and the processing path can vary depending on some condition. Forexample in a given state A, the next state may be state B (which uses aCompleteSelf() call to get there) or state C (which is entered once anasynchronous request completes) depending on some condition.194ACTIVE OBJECTSChecking the state need not only be done in the RunL(). For example,the DoCancel() function in our example checks to see if the timer needsto be cancelled.void CMultiPartHello::DoCancel(){switch( iState ){case EHideHello:case EShowHello:{iTimer.Cancel();break;}default:break;}ShowText(ETrue);iState = EIdle;}Looking back at RunL(), we can see that the timer was started in theShow Hello state and then the state changed to Hide Hello. Similarlyin Wait State, the state was changed to Show Hello once the timerwas started.

The timer is only cancelled if the state machine is in theHide Hello or Show Hello states.6.11Long-Running Tasks and Active ObjectsSometimes, you want to be able to implement a long-running taskalongside your application’s (or server’s) main task. In other operatingsystems you might implement such a task with a background thread.In Symbian OS, the best way to implement such a task is with a lowpriority active object that runs in the idle time of other event-handlingactive objects. It is essentially a low-priority state machine that alwayscompletes itself.

The paradigm for a long-running task is:• Design a state machine to do the background task through a series ofstates.• In the Start() function, use a self-complete function to make yourobject eligible for its RunL() function to be called the next timecontrol returns to the active scheduler.• When RunL() is called, you should do some processing for thelong-running task. Remember that you should keep the processingto a realistic amount so as not to block higher-priority active objectsfrom having a chance to handle their events.LONG-RUNNING TASKS AND ACTIVE OBJECTS195• If the task is not complete, then it needs to self-complete to continueprocessing. If the task is complete, it should simply stop and notcomplete any more.• In DoCancel(), you may wish to destroy any intermediate dataassociated with the long-running task.

You do not need to issue acall to User::RequestComplete() because you already did thatfrom either Start() or RunL(). Remember, any request you issueshould be completed precisely once, so you do not need to completeit again.A very simple long-running task would be a Fibonacci number generator. Starting with the numbers 0 and 1, each successive number is thesum of the two preceding numbers (see Figure 6.12).Figure 6.12 Fibonacci program running on S60 3rd editionThe Fibonacci number generator can be represented as an idle-timecalculation that calculates the next number in the sequence when noother active object is ready to run.The following code implements this simple algorithm.

Since the numbers become very large, very quickly, it only generates the first 80numbers in the sequence. After they have been generated, the activeobject begins the sequence again, starting from zero.First, we define a means of displaying the result of the current calculation on the screen:class MFibonacciResultHandler{public:virtual void HandleFibonacciResultL(const TUint64& aResult)=0;virtual void HandleFibonacciCalculatorResetL()=0;};196ACTIVE OBJECTSThis is a pure virtual ‘mixin’ class, which the client of the active objectmust implement.

In this particular case, we implement it inside our mainview control so that we can draw the generated number, aResult,to the display. To report the calculated number, the active object callsthe HandleFibonacciResultL() function. The secondary purposeof the mixin is to provide a means of telling the user interface (UI) thatthe active object is about to restart calculation again from the beginningof the sequence, once 80 numbers have been calculated. The engine caninform the UI that calculations are going to be restarted by calling theHandleFibonacciCalculatorResetL() function.Next, we declare the active object:class CFibonacciGenerator : public CActive{public:// Construct/destructstatic CFibonacciGenerator* NewL(MFibonacciResultHandler&aResultHandler);∼CFibonacciGenerator();// Requestvoid Start();private:// Construct/destructCFibonacciGenerator(MFibonacciResultHandler& aResultHandler);void ConstructL();// from CActivevoid RunL();void DoCancel();TInt RunError(TInt aError);// Internal methodsvoid Reset();void CompleteSelf();private:MFibonacciResultHandler& iResultHandler;TUint64 iMostRecentResult;TUint64 iOldestResult;TUint iSequenceNumber;};The static constructor, NewL(), has a reference to the new resulthandler interface so that when a number is calculated the handler canreceive the generated number.CFibonacciGenerator::CFibonacciGenerator(MFibonacciResultHandler& aResultHandler): CActive(EPriorityIdle),iResultHandler(aResultHandler){CActiveScheduler::Add(this);}void CFibonacciGenerator::ConstructL(){// Empty on this occasion}LONG-RUNNING TASKS AND ACTIVE OBJECTS197The constructor of the class has several purposes.

First, it definesthe active object priority as CActive::EPriorityIdle, so that thisobject’s RunL() only executes when there are no higher-priority eventsto be handled. Secondly, it stores a reference to the result handler inthe iResultHandler data member so that we can use this to reporta calculation result later on. Finally, it adds the object to the activescheduler. The second-phase constructor, ConstructL(), is empty inthis instance since no further object initialization is required.The Start() function is responsible for starting the idle-time calculation.void CFibonacciGenerator::Start(){Reset();CompleteSelf();}const TUint KFibonacciSeedNumberFirst = 0;const TUint KFibonacciSeedNumberSecond = 1;void CFibonacciGenerator::Reset(){iSequenceNumber = 0;iOldestResult = KFibonacciSeedNumberFirst;iMostRecentResult = KFibonacciSeedNumberSecond;// Notify our result handler that we have restarted// our calculationTRAP_IGNORE (iResultHandler.HandleFibonacciCalculatorResetL());}Start() calls the Reset() function, which initializes the seed numbers to their starting values of 0 and 1, as well as resetting the sequencenumber to 0.

The iSequenceNumber contains a counter value thatindicates how many numbers in the sequence we have calculated so far.A Fibonacci sequence begins with the numbers zero and one, so we mustalways ensure we inform the UI of these two numbers before attemptingto calculate the third. We also make a call to our result handler to informit that we are about to begin calculating the sequence again from thestart, using iResultHandler. HandleFibonacciCalculatorResetL(). This allows the UI to reset itself ready for the start of a newsequence.Start() then calls the CompleteSelf() utility function to complete the active object’s request status and set the object as active.void CFibonacciGenerator::CompleteSelf(){TRequestStatus* status = &iStatus;User::RequestComplete(status, KErrNone);SetActive();}198ACTIVE OBJECTSWe do not need to include a line that sets the value of iStatus toKRequestPending. The call to User::RequestComplete() doesthat for us.

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

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

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

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