Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 35

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 35 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 352018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

By defaulton Symbian OS, each thread has its own independent heap as well asits own stack. The size of the stack is limited to the size you set inRThread::Create(), but the heap can grow from its minimum sizeup to a maximum size, which is why both values may be specified in oneof the overloads of Create().3 Where the thread has its own heap, thestack and the heap are located in the same chunk of memory.When the thread is created, it is assigned a unique thread identity,which is returned by the Id() function of RThread as a TThreadIdobject. If you know the identity of an existing thread, you can pass itto RThread::Open() to open a handle to that thread.

Alternatively,you can use an overload of the Open() function to pass the uniquename of a thread on which to open a handle. The thread’s name is setas a parameter of the Create() function overloads when the thread iscreated; once you have a handle to a thread, it is possible to rename itusing RThread::Rename() if the thread is not protected.RThread has been modified in releases of Symbian OS v8.0 toprotect threads against abuse from potentially malicious code.10.2 Thread PrioritiesOn Symbian OS, threads are pre-emptively scheduled and the currentlyrunning thread is the highest priority thread ready to run. If there are two3You can also specify the minimum and maximum heap size for the main thread of acomponent that runs as a separate process in its .mmp file, using the following statement:epocheapsize minSizeInBytes maxSizeInBytes156SYMBIAN OS THREADS AND PROCESSESor more threads with equal priority, they are time-sliced on a round-robinbasis. The priority of a thread is a number: the higher the value, the higherthe priority.When writing multithreaded code, you should consider the relativepriorities of your threads carefully.

You should not arbitrarily assign athread a high priority, otherwise it may pre-empt other threads in thesystem and affect their response times. Even those threads which maylegitimately be assigned high priorities must endeavor to make theirevent-handling service complete rapidly, so they can yield the systemand allow other threads to execute.A thread has an absolute priority which is calculated from the priorityassigned to the thread by a call to RThread::SetPriority() andoptionally combined with the priority assigned to the process in whichit runs.

The TThreadPriority and TProcessPriority enumerations, taken from e32std.h, are shown below.enum TThreadPriority{EPriorityNull=(-30),EPriorityMuchLess=(-20),EPriorityLess=(-10),EPriorityNormal=0,EPriorityMore=10,EPriorityMuchMore=20,EPriorityRealTime=30,EPriorityAbsoluteVeryLow=100,EPriorityAbsoluteLow=200,EPriorityAbsoluteBackground=300,EPriorityAbsoluteForeground=400,EPriorityAbsoluteHigh=500};enum TProcessPriority{EPriorityLow=150,EPriorityBackground=250,EPriorityForeground=350,EPriorityHigh=450,EPriorityWindowServer=650,EPriorityFileServer=750,EPriorityRealTimeServer=850,EPrioritySupervisor=950};The following values are relative thread priorities: EPriorityMuchLess, EPriorityLess, EPriorityNormal, EPriorityMore andEPriorityMuchMore.

If these values are passed to RThread::SetPriority(), the resulting absolute priority of the thread is the combination of the priority of the process and the relative value specified. Forexample, if the process has TProcessPriority::EPriorityHigh(=450), and SetPriority() is called with TThreadPriority ofEPriorityMuchLess, the absolute priority of the thread will beSTOPPING A RUNNING THREAD157450 − 20 = 430. If, for the same process, TThreadPriority::EPriorityMuchMore is passed to SetPriority() instead, the absolute priority of the thread will be 450 + 20 = 470.The remaining TThreadPriority values, except EPriorityRealTime,4 are absolute priorities that allow the priority of the threadto be independent of the process in which it is running.

If thesevalues are passed to a call to RThread::SetPriority(), the priority of the thread is set to the value specified, and the processpriority is ignored. For example, if the process has TProcessPriority::EPriorityHigh (=450), the absolute priority of thethread can range from EPriorityAbsoluteVeryLow (=100) toEPriorityAbsoluteVeryHigh (=500), depending on the absoluteTThreadPriority value selected.All threads are created with priority EPriorityNormal by default.When a thread is created it is initially put into a suspended state and doesnot begin to run until Resume() is called on its handle. This allows thepriority of the thread to be changed by a call to SetPriority() beforeit starts to run, although the priority of a thread can also be changed atany time.The secure RThread class in EKA2 does not allow you to call SetPriority() on a handle to any thread except that in which the code iscurrently running. This prevents a badly programmed or malicious threadfrom modifying the priorities of other threads in the system, which mayhave a serious effect on the overall system performance.10.3 Stopping a Running ThreadA running thread can be removed from the scheduler’s ready-to-run queueby a call to Suspend() on its thread handle.

It still exists, however, andcan be scheduled to run again by a call to Resume(). A thread canbe ended permanently by a call to Kill() or Terminate(), both ofwhich take an integer parameter representing the exit reason. You shouldcall Kill() or Terminate() to stop a thread normally, reservingPanic() for stopping the thread to highlight a programming error. If themain thread in a process is ended by any of these methods, the processterminates too.On EKA1, a thread must call SetProtected() to prevent otherthreads from acquiring a handle and stopping it by calling Suspend(),Panic(), Kill() or Terminate(). On EKA2, the security modelensures that a thread is always protected and the redundant SetProtected() method has been removed.

This default protection ensures4TThreadPriority::EPriorityRealTime is treated slightly differently. Passingthis value to SetPriority() causes the thread priority to be set to TProcessPriority::EPriorityRealTimeServer.158SYMBIAN OS THREADS AND PROCESSESthat it is no longer possible for a thread to stop another thread in aseparate process by calling Suspend(), Terminate(), Kill() orPanic() on it.

The functions are retained in EKA2 because a threadcan still call the various termination functions on itself or other threadsin the same process. RMessagePtr has Kill(), Terminate() andPanic() methods that are identical to those in RThread. These allowa server to terminate a client thread, for example to highlight a programming error by causing a panic in a client which has passed invalidrequest data. Chapters 11 and 12 discuss the client–server framework inmore detail.The manner by which the thread was stopped, and its exit reason,can be determined from the RThread handle of an expired thread bycalling ExitType(), ExitReason() and ExitCategory().

The exittype indicates whether Kill(), Terminate() or Panic() was calledor, indeed, if the thread is still running. The exit reason is the integerparameter value passed to the Kill() or Terminate() functions,or the panic reason. The category is a descriptor containing the paniccategory, ”Kill” or ”Terminate”. If the thread is still running, the exitreason is zero and the exit category is a blank string.It is also possible to receive notification when a thread dies. A call toRThread::Logon() on a valid thread handle, passing in a TRequestStatus reference, submits a request for notification when that thread terminates.

The request completes when the thread terminates and receivesthe value with which the thread ended or KErrCancel if the notificationrequest was cancelled by a call to RThread::LogonCancel().The following example code, which is suitable both for EKA1 andEKA2, demonstrates how you may use thread termination notification. Itshows how some long-running synchronous function (SynchronousTask()) can be encapsulated within an active object class whichruns the task in a separate thread, allowing the function to be calledasynchronously. This is useful if a caller doesn’t want to be blockedon a slow-to-return synchronous function. For example, a third-partylibrary may provide a synchronous API for preparing a file for printing.

The UI code which uses it cannot just ”hang” while waiting forthe function to return; it requires the operation to be performed asynchronously. Of course, ideally, the function would be asynchronous,implemented incrementally in a low-priority active object, as describedin Chapter 9. However, some tasks cannot easily be split into small unitsof work, or may be ported from code which was not designed for activeobjects.The class defined below supplies an asynchronous wrapper, DoAsyncTask(), over a synchronous function, allowing the caller to submit anasynchronous request and receive notification of its completion througha TRequestStatus object.STOPPING A RUNNING THREAD159_LIT(KThreadName, "ExampleThread"); // Name of the new threadTInt SynchronousTask(); // Example of a long-running synchronous functionclass CAsyncTask : public CActive{// Active object class to wrap a long synchronous taskpublic:∼CAsyncTask();static CAsyncTask* NewLC();// Asynchronous request functionvoid DoAsyncTask(TRequestStatus& aStatus);protected: // From base classvirtual void DoCancel();virtual void RunL();virtual TInt RunError(TInt anError);private:CAsyncTask();void ConstructL();// Thread start functionstatic TInt ThreadEntryPoint(TAny* aParameters);private:TRequestStatus* iCaller; // Caller’s request statusRThread iThread;// Handle to created thread};The implementation of the active object class is shown below.DoAsyncTask() is the asynchronous request-issuing function into whichthe caller passes a TRequestStatus object, typically from another activeobject, which is stored internally as iCaller by the function.

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

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

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

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