Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 22

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 22 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 222018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

You haveto loop while testing the condition since there is no guarantee that thecondition has been satisfied when the condition variable is signaled.Different threads may be waiting on different conditions or the conditionmay have already been absorbed by another thread. All that can be saidis that the thread will awaken whenever something happens which mightaffect the condition.And what about the producer thread? How does it signal the conditionvariable? There are two methods in RCondVar that allow it to do this:Signal() and Broadcast().Signal() unblocks a single, waiting thread. If there are several ofthese, then the kernel unblocks the highest-priority thread that is notexplicitly suspended.

If there are no threads currently waiting this calldoes nothing.The calling thread does not have to hold the mutex when it callsSignal() but we recommend that it does so. Otherwise a race conditioncan result if it signals the condition variable just between the waitingthread testing the condition and calling Wait().Broadcast() unblocks all the threads that are waiting on the condition variable. As for Signal(), it is best if the thread that callsBroadcast() holds the mutex first.I hope that I have also shown that, although RCondVar is usedfor explicit communications between threads, the communications areanonymous. The producer thread does not necessarily know that theconsumer thread is waiting on the condition variable that it signaled.

Andthe consumer thread does not know that it was the producer thread thatwoke it up from its wait on the condition variable.3.3.8 Symbian OS thread deathAll Symbian OS threads have an exit handler installed, which performsfirst stage cleanup of the thread in the context of the exiting thread. Thisfirst stage includes:• Restoring the thread to a consistent state – for example removing thethread from any mutexes or semaphores on which it was waiting• Running thread-exit cleanup handlers• Completing logons.SYMBIAN OS THREADS89The kernel can’t perform its entire cleanup in the exiting thread’s context – for example it can’t free the thread’s supervisor stack or controlblock. So the kernel performs a second phase of exit processing inthe supervisor thread context.

Each DThread has a DFC, given byiKillDfc, which is queued on the supervisor thread just before theexiting thread actually terminates. The DFC completes the cleanup process – closing thread handles, freeing stacks and freeing the thread controlblock. If this is the last thread in a process, then it also closes processhandles and frees the process control block.3.3.8.1 Types of Symbian OS threadWhen we start to think about thread death, there are four different typesof Symbian OS thread we need to consider.

These are specified by theiFlags member data, and defined in u32std.h:KThreadFlagProcessCritical = 1KThreadFlagProcessPermanent = 2KthreadFlagSystemCritical = 4KthreadFlagSystemPermanent = 8The corresponding user-side enumerations are in e32std.h:enum TCritical{ENotCritical,EProcessCritical,EProcessPermanent,EAllThreadsCritical,ESystemCritical,ESystemPermanent};The meanings of the values in this enumeration are:ENotCriticalThe thread or process is not critical. No special action is taken on threador process exit or panic.EProcessCriticalIndicates that a thread panic causes the process to panic.EProcessPermanentIndicates that a thread exit of any kind causes the process to exit.EAllThreadsCriticalIndicates that if any thread in a process panics, then the process panics.90THREADS, PROCESSES AND LIBRARIESESystemCriticalIndicates that a thread or process is system-critical.

If that thread orprocess panics, then the entire system is rebooted. Clearly this is a drasticstep to take, so we ensure that only a process with the ‘‘Protected Server’’capability can set a thread to system-critical.ESystemPermanentIndicates that a thread or process is system-permanent. If that thread orprocess exits, then the entire system is rebooted. Clearly this too is adrastic step to take, so again we ensure that only a process with the‘‘Protected Server’’ capability can set a thread to system-permanent.3.3.9Kernel threadsThe Symbian OS kernel itself creates five kernel threads at boot time,and these threads continue to run until the mobile phone is rebooted. (Infact, there may even be more than five threads on a phone, since kernelextensions can create them too.) Next I will briefly describe each kernelthread and its purpose in the system.3.3.9.1 The null threadEarlier I described how the null thread (also known as the idle thread) isthe first thread to run on a device at boot time.

This thread’s executionbegins at the reset vector. Just after the reset is applied, there are noNThread or DThread objects in existence, of course – but the thread ofexecution that begins here eventually becomes the null thread, which isthe thread with the lowest possible priority in the system. Since there isno point in time slicing the null thread, the kernel sets a variable in thethread to disable time slicing. This thread has iType==EInitial, andis the only thread in the system with this type.Because of the unusual way this thread comes into being, the bootstrapmust allocate and map its stack before kernel execution begins.

Thismeans that the stack is in a special place – at the start of the chunkcontaining the kernel heap. For more on Symbian OS bootup, seeChapter 16, Boot Processes.As we said, the null thread has the lowest possible priority in thesystem. This means that the null thread will gain control only whenno other thread is ready to run. Generally the null thread simply loopsforever executing a ‘‘wait for interrupt’’ instruction, which places the CPUin a low-power mode where instruction execution stops until a hardwareinterrupt is asserted.The main task that the null thread performs in its infinite loop is todelay the nanokernel timer tick for as long as possible.

The null threadinspects the nanokernel timer queue and determines how many ticks willSYMBIAN OS THREADS91elapse before the first timer is due to expire. It then updates the hardwaretimer to skip that number of ticks, so that the next timer interrupt coincideswith the expiry of the first timer on the queue. In this way, we save powerby not reactivating the CPU several times just to discover that there isnothing to be done.

For more details of Symbian OS power management,see Chapter 15, Power Management.3.3.9.2 The supervisor threadThis is the second thread to run after a system reset. It is responsiblefor the final phase of kernel initialization and for phase 3 of the variantinitialization, which initializes the interrupt dispatcher and enables thenanokernel tick timer interrupt.

For more details of the supervisor thread’srole in start-up, see Chapter 16, Boot Processes.Once the OS is running, the primary functions of the supervisor threadare cleanup activities and providing notification of non-time-criticalevents to user-side code. The supervisor thread’s priority is set so thatit is higher than applications and most user-mode code but lower thananything that is time-critical.The supervisor thread performs many of its functions via deferredfunction calls, or DFCs, which I will discuss in Chapter 5, Interrupts andExceptions.

DFCs that run in the supervisor thread can’t expect any realtime guarantees – and would typically be unbounded operations anyway,often involving the freeing of memory. To sum up, DFCs in the supervisorthread perform these tasks:1. Thread and process cleanup on exit2. Asynchronous deletion. For more on this, see Chapter 7, MemoryModels3. Asynchronous change notifier completion. (User code uses theRChangeNotifier class to get notification from the kernel ofimportant changes, such of change of locale.) Sometimes the kernelneeds to signal change notifiers either from time-critical code (forexample the midnight crossover detection in TSecondQ) or fromplaces where low-level kernel mutexes are held (for example thememory threshold detection code may run with the kernel heapmutex held). The signaling of change notifiers is unbounded (sincethere may be arbitrarily many of them) and involves waiting on thechange notifier container’s mutex.

To avoid timing and deadlockproblems, the kernel provides the function Kern::AsyncNotifyChanges(). This function accumulates the set of changes that itneeds to signal in a bit mask, K::AsyncChanges, and queues aDFC on the supervisor thread to signal the change notifiers92THREADS, PROCESSES AND LIBRARIES4.Asynchronous freeing of physical RAM.

For more on this, seeChapter 7, Memory Models5.The completion of publish and subscribe property subscriptions.3.3.9.3 DFC thread 0This thread has priority 27 (usually the second highest in the system), andit simply runs a DFC queue. The kernel does not use this queue itself, butprovides it for those device drivers that do not have stringent real-timerequirements, to give them a context that they can use for their non-ISRprocessing.

You can think of this queue as approximately equivalent tothe single DFC queue that EKA1 provided. The presence of this single‘‘general purpose’’ DFC thread in the kernel saves memory, becauseeach device driver does not have to create its own thread. The functionKern::DfcQue0() returns a pointer to the DFC queue serviced bythis thread.Symbian device drivers that use this thread include serial comms,sound, ethernet, keyboard and digitizer.3.3.9.4 DFC thread 1This thread has priority 48; it is generally the highest-priority thread inthe system. The nanokernel timer DFC runs on this thread.DFC thread 1 is available for use by other device drivers if necessary;the function Kern::DfcQue1() returns a pointer to the DFC queueserviced by this thread.You should beware of using DFC thread 1 for anything other thanrunning the nanokernel timer queue.

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

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

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

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