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

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

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

For implementationreasons, there must be at least one asynchronous request issued before theloop starts, otherwise the thread simply enters the wait loop indefinitely.Let’s look at why this happens in more detail by examining the activescheduler wait loop:ACTIVE OBJECTS711. When it is not handling other completion events, the active scheduler suspends a thread by calling User::WaitForAnyRequest(),which waits for a signal to the thread’s request semaphore.2. If no events are outstanding in the system entirely, it is at this pointthat the OS can power down to sleep.3. When an asynchronous server has finished with a request, it indicatescompletion by calling User::RequestComplete() (if the serviceprovider and requestor are in the same thread) or RThread::RequestComplete() otherwise.

The TRequestStatus associated with the request is passed into the RequestComplete()method along with a completion result, typically one of the standarderror codes.4. The RequestComplete() method sets the value of TRequestStatus to the given error code and generates a completion event inthe requesting thread by signaling a semaphore.5.

When a signal is received and the thread is next scheduled, the activescheduler determines which active object should handle it. It checksthe priority-ordered list of active objects for those with outstandingrequests (these have their iActive Boolean set to ETrue as a resultof calling CActive::SetActive()).6. If an object has an outstanding request, the active scheduler checksits iStatus member variable to see if it is set to a value otherthan KRequestPending. If so, this indicates that the active objectis associated with the completion event and that the event handlercode should be called.7. The active scheduler clears the active object’s iActive Booleanand calls its RunL() event handler.8. Once the RunL() call has finished, the active scheduler re-enters theevent processing wait loop by issuing another User::WaitForAnyRequest() call.

This checks the thread’s request semaphoreand either suspends it (if no other events need handling) or returnsimmediately to lookup and event handling.The following pseudo-code illustrates the event-processing loop:EventProcessingLoop(){// Suspend the thread until an event occursUser::WaitForAnyRequest();// Thread wakes when the request semaphore is signaled// Inspect each active object added to the scheduler,// in order of decreasing priority// Call the event handler of the first which is active & completed72SYMBIAN OS DEVELOPMENT BASICSFOREVER{// Get the next active object in the priority queueif (activeObject->IsActive())&&(activeObject->iStatus!=KRequestPending){// Found an active object ready to handle an event// Reset the iActive status to indicate it is not activeactiveObject->iActive = EFalse;// Call the active object’s event handler in a TRAPTRAPD(r, activeObject->RunL());if (KErrNone!=r){// event handler left, call RunError() on active objectr = activeObject->RunError();if (KErrNone!=r) // RunError() didn’t handle the error,Error(r);// call CActiveScheduler::Error()}break; // Event handled, break out of lookup loop and resume}} // End of FOREVER loop}3.15.5 Common Problems with Active ObjectsStray signal panicsThe most common problem when writing active objects is when youencounter a stray signal panic (E32USER-CBASE 46).

These occur whenan active scheduler receives a completion event but cannot find an activeobject to handle it. Stray signal panics are notoriously extremely difficultto debug. Stray signals can occur because:• CActiveScheduler::Add() was not called when the active objectwas constructed.• SetActive() was not called after submitting a request to an asynchronous service provider. You usually only need to add the activeobject to the active scheduler once, however, it is common to reusean active object several times to make several asynchronous requestsand it needs to be reactivated every single time.• The asynchronous service provider completed the request more thanonce, which is unlikely when using a Symbian OS system server, butconceivable when using a third-party server.If you receive a stray signal panic, the first thing to do is work outwhich active object is responsible for submitting the request that latergenerates the stray event.

One of the best ways to do this is to use filelogging in every active object and, if necessary, eliminate them from yourcode one by one until the culprit is tracked down.THREADS73Unresponsive UIIn an application thread, in particular, event-handler methods must bekept short to allow the UI to remain responsive to the user.

No singleactive object should have a monopoly on the active scheduler since thatprevents other active objects from handling events. Active objects mustcooperate and should not:• Have lengthy RunL() or DoCancel() methods.• Repeatedly resubmit requests that complete rapidly, particularly if theactive object has a high priority, because the event handler will beinvoked at the expense of lower-priority active objects waiting to behandled.• Have a higher priority than is necessary.Other causes of an unresponsive UI are temporary or permanent threadblocks that result because of:• A call to User::After(), which stops the thread executing for thelength of time specified.• Incorrect use of the active scheduler. There must be at least oneasynchronous request issued, via an active object, before the activescheduler starts.

If no request is outstanding, the thread simply entersthe wait loop and sleeps indefinitely.• Incorrect use of User::WaitForRequest() to wait on an asynchronous request, rather than correct use of the active object framework.3.16 ThreadsIn many cases on Symbian OS, it is preferable to use active objects ratherthan threads, since these are optimized for event-driven multitasking onthe platform. However, when you are porting code written for other platforms, or writing code with real-time requirements, it is often necessaryto write multithreaded code. The Symbian OS class used to manipulatethreads is RThread, which represents a handle to a thread; the threaditself is a kernel object.The RThread class defines several functions for thread creation, eachof which takes a descriptor for the thread’s name, a pointer to a functionin which thread execution starts, a pointer to data to be passed to thatfunction (if any), and the stack size of the thread.

RThread::Create()is overloaded to allow for different heap behavior, such as definition of74SYMBIAN OS DEVELOPMENT BASICSthe thread’s maximum and minimum heap size or whether it shares thecreating thread’s heap or uses a separate heap.A thread is created in the suspended state and its execution initiated by calling RThread::Resume(). On Symbian OS, threadsare preemptively scheduled and the currently running thread is thehighest-priority thread ready to run. If there are two or more threadswith equal priority, they are time-sliced on a round-robin basis.

Arunning thread can be removed from the scheduler’s ready-to-run queueby a call to RThread::Suspend(). It can be restarted by callingResume(). To terminate a thread permanently, you should call Kill()or Terminate() – to stop it normally – and Panic() to highlight aprogramming error.Please see the Symbian Developer Library for more information aboutworking with Symbian OS threads. Example code is also provided in theSDK to show the use of RThread and other Symbian OS system classes.3.17Timers and CallbacksThe RTimer class provides a very useful service and one of the simplest ways of making an asynchronous request is to use an activeobject: RTimer::After() is the asynchronous request and RTimer::Cancel() is used to cancel the request if, for example, the applicationis closed before the kernel completes the request.RTimer::AtUTC() is a good way to implement alarms on yourphone and RTimer::Inactivity() can be used both to save batterylife and to prevent the phone’s keyboard and screen from locking.Another useful class is TCallback, which is really just a fancy wayof saying ‘method pointer’.

Actually, TCallback can only represent astatic non-leaving method that must return an integer and have exactlyone pointer parameter, which can be cast to a known type in order toaccess its methods.TCallback is used by two different specialized active objects thatregenerate their own asynchronous requests: CPeriodic and CIdle.Both of them will be reactivated by the time their RunL() method returns.In both cases, RunL() is already overwritten and calls the TCallbackyou define.CPeriodic::Start() uses a kernel timer to decide when its requestwill be completed.CIdle is a fairly strange exception amongst active objects: its requestis not really asynchronous as it is already completed by the timeCIdle::Start() returns.

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

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

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

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