Главная » Просмотр файлов » 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), страница 20

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

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

But, of course a thread mayhave any number of logons outstanding, and canceling a logon requiresthe kernel to walk the list of outstanding logons. This means that the timefor which the system lock could be held is unbounded.You might be wondering why this is so. After all, the kernel releases thesystem lock after it processes each cleanup item.

However, the situationsare subtly different. The kernel processes cleanup items when a threadexits, walking the queue and processing each cleanup item. However,rather than searching for and removing a particular item, it simply wantsto remove all items, so it can use an algorithm like this one:FOREVER{LOCK();// remove the first item (if any) from the list78THREADS, PROCESSES AND LIBRARIES// and return a pointer to it.// p is null when there are no more items leftp = GetFirstItem();UNLOCK();if (p)Cleanup(p);elsebreak;}But when attempting to cancel a logon, the kernel needs to search thelist for a particular item and remove just that one item.

If it releases thelock at any point during this scan it can ‘‘lose its place’’ – the last itemit checked may be removed from the list and placed on another list, oreven destroyed, before this portion of code runs again. So the kernel musthold the lock throughout the scan, and this means that it cannot use thesystem lock.We also considered the fact that processes don’t have cleanup queues.Once we had taken this into account, it made sense to create an entirelynew mechanism for thread logons, knowing we could re-use it for processlogons.

So, we use a separate queue for logons, and we protect this queuewith a different mutex.3.3.7 Symbian OS thread-synchronization objectsThe Symbian OS kernel provides support for more complex threadsynchronization objects than the nanokernel does. These objects areSymbian OS semaphores and mutexes.Symbian OS semaphores are standard counting semaphores whichsupport multiple waiting threads (unlike nanokernel fast semaphores) andwhich release waiting threads in priority order.Symbian OS mutexes are fully nestable – a thread can hold severalmutexes at once and can also hold the same mutex several times.

Theysupport priority inheritance – the holding thread inherits the priority of thehighest-priority waiting thread if that is higher than the holding thread’susual priority. The kernel and memory model use Symbian OS mutexesextensively to protect long-running critical code sections.3.3.7.1 Semaphores – DSemaphoreSymbian OS semaphores are standard counting semaphores. The semaphore maintains a count: if the count is positive or zero, no threadsare waiting; if it is negative, the count is equal to minus the number ofwaiting threads.There are two basic operations on semaphores:SYMBIAN OS THREADS79• WAIT. This decrements the count atomically.

If the count remains nonnegative the calling thread continues to run; if the count becomesnegative the calling thread is blocked• SIGNAL. This increments the count atomically. If the count wasoriginally negative, the kernel releases the next waiting thread.The kernel protects Symbian OS semaphore operations by the systemlock.It is important to note that DSemaphore operations rely on fieldsthat are present in DThread but not in NThread. This means that onlySymbian OS threads may invoke Symbian OS semaphore operations – itis not permitted for an IDFC or a non-Symbian OS thread to signal aSymbian OS semaphore.We use the DSemaphore class to represent a Symbian OS semaphore.This class is derived from DObject, which makes it a dynamicallyallocated reference counted object.

DSemaphore is the kernel objectreferred to by a user-side RSemaphore handle:class DSemaphore : public DObject{public:TInt Create(DObject* aOwner, const TDesC* aName,TInt aInitialCount, TBool aVisible=ETrue);public:∼DSemaphore();void WaitCancel(DThread* aThread);void WaitCancelSuspended(DThread* aThread);void SuspendWaitingThread(DThread* aThread);void ResumeWaitingThread(DThread* aThread);void ChangeWaitingThreadPriority(DThread* aThread, TInt aNewPriority);public:TInt Wait(TInt aNTicks);void Signal();void SignalN(TInt aCount);void Reset();public:TInt iCount;TUint8 iResetting;TUint8 iPad1;TUint8 iPad2;TUint8 iPad3;SDblQue iSuspendedQ;TThreadWaitList iWaitQ;public:friend class Monitor;};Key member data of DSemaphoreiCountThe semaphore count.80THREADS, PROCESSES AND LIBRARIESiResettingA flag set while the semaphore is being reset; this occurs just priorto the semaphore being deleted and involves releasing any waiting orsuspended threads.

The flag is used to prevent any more threads fromwaiting on the semaphore.iSuspendedQThis is a doubly linked list of threads which are both waiting on thesemaphore and explicitly suspended. These threads will have iWaitObjpointing to this semaphore and will have M-state EWaitSemaphoreSuspended.iWaitQA list, in decreasing priority order, of threads that are waiting on thesemaphore and not explicitly suspended. Note that this is a differencefrom EKA1 – under the old version of Symbian OS, the kernel releasedthreads in the order that they had waited on the semaphore.Threads in this list will have their iWaitObj pointing to this semaphoreand their M-state will be EWaitSemaphore.Note that the iWaitObj field under discussion here is the DThreadmember, not the NThread member of the same name.Threads that are explicitly suspended as well as waiting on a semaphoreare not kept on the semaphore wait queue; instead, the kernel keeps themon a separate suspended queue, iSuspendedQ, which is just a standarddoubly linked list.

We do not regard such threads as waiting for thesemaphore – if the semaphore is signaled, they will not acquire it andthe semaphore count will simply increase and may become positive.To acquire the semaphore, they must be explicitly released, at whichpoint the kernel removes them from iSuspendedQ and adds them toiWaitQ.3.3.7.2 Mutexes – DMutexSymbian OS mutexes provide mutual exclusion between threads, butwithout the restrictions imposed by the nanokernel mutex. So,• It is possible to wait on a Symbian OS mutex multiple times, providedit is signaled the same number of times• It is possible to hold several Symbian OS mutexes simultaneously,although care is required to avoid deadlocks (I’ll discuss this later)• It is possible to block while holding a Symbian OS mutex.

SymbianOS mutexes provide priority inheritance.SYMBIAN OS THREADS81The freedom from the restrictions of the nanokernel mutex comes at aprice in terms of performance; operations on Symbian OS mutexes aremore complicated and hence slower than those on NFastMutex.Our motivation in designing DMutex was the requirement that themutex should be held, whenever possible, by the highest priority threadthat requires the mutex. Of course, this is not possible if the mutex isalready held when a higher-priority thread requests the mutex – in thiscase, the delay before the higher-priority thread acquires the mutex shouldbe kept to a minimum.

The design meets these criteria in these ways:1. The kernel defers a thread’s acquisition of a mutex to the last possiblemoment. A thread cannot acquire a mutex on behalf of anotherthread; it can only acquire a mutex for itself.

When a thread signalsa mutex, the kernel does not directly hand the mutex over to thehighest-priority waiting thread; it merely frees the mutex and releasesthe highest-priority waiting thread. The waiting thread must actuallyrun to claim the mutex. We chose this design to take care of thecase in which a high-priority thread acquires and releases a mutexseveral times in succession. Imagine we have a high-priority threadHAIKU that owns a mutex and a lower-priority thread EPIC that is thehighest-priority thread waiting on that mutex. If HAIKU released themutex and the kernel then handed it over to EPIC immediately, thenHAIKU would not be able to reclaim the mutex so would be delayedby the lower-priority thread2.

The kernel queues threads waiting for a mutex and releases themin priority order. So when the kernel releases a mutex the highestpriority waiting thread will run and acquire the mutex, if its priorityis higher than the current thread’s priority3. Mutexes implement priority inheritance. If a low priority thread, EPIC,is holding a mutex when a higher-priority thread, HAIKU, waits onthe same mutex, then the kernel elevates the priority of EPIC to thatof HAIKU. This ensures that another thread SONNET, of mediumpriority, which might prevent EPIC from running and releasing themutex, does not delay HAIKU4. If the kernel suspends a thread that is waiting on a mutex, it removesit from the wait queue and places it on a separate suspended queue.The kernel no longer regards the thread as waiting for the mutex: thekernel will never hand over the mutex to a thread that is suspended.This is because this would result in the mutex being held for anindeterminate period.We need three thread M-states to describe the interaction of a threadwith a mutex.

The most obvious of these is the EWaitMutex state, which82THREADS, PROCESSES AND LIBRARIESindicates that the thread is blocked waiting for the mutex. The kernel addsa thread in EWaitMutex state to the priority-ordered mutex wait queue.Point 4 requires the existence of a second state, EWaitMutexSuspended; this is because threads that are both waiting for a mutex andexplicitly suspended are not enqueued on the wait queue but on thesuspended queue.

The kernel needs to perform different actions in theevent, for example, of the thread being killed, and so different statesare required.Point 1 requires the existence of a third state, EHoldMutexPending.When the kernel releases a mutex, it marks the mutex as free and releasesthe highest-priority waiting thread. Typically, that thread will then runand acquire the mutex. Note that although there may be other threads onthe wait queue, we release only one thread, the highest priority one. Wedo this for efficiency – there is no point releasing all those other threadssince this is time-consuming and only the highest-priority thread amongthem will be able to acquire the mutex anyway.

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

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

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

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