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

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

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

This could lead to problems: imaginethat thread MARLOW is in the middle of updating a global data structure,when thread BACON preempts it. Then the global data structure is leftin a half-modified state, and if BACON tries to access that data a systemcrash may well result. We can guard against this scenario by protectingeach such global data structure by a mutex, but we need to do morethan this.Imagine this time that, while MARLOW is in the middle of updating theglobal data structure, BACON preempts MARLOW and suspends or killsit. Let’s consider the two situations – suspended or killed – separately.Assume BACON suspended MARLOW, and that BACON is the onlythread that might release MARLOW. MARLOW still holds the mutexprotecting the global data structure. So now, if BACON tries to access thesame global data structure, a deadlock results, because no other threadwill release MARLOW.Assume BACON killed MARLOW.

Now we have a situation similarto our first one – we have left the global data structure in a half-modifiedstate, rendering it unusable by any other thread and having the potentialto crash the entire system.To prevent either of these situations from occurring, we give eachthread a critical section count, iCsCount. We increment this every timethe thread enters a critical section of kernel code, and decrement it whenthe thread leaves the critical section.56THREADS, PROCESSES AND LIBRARIESThen, when thread BACON preempts thread MARLOW, and tries tosuspend or kill it, the nanokernel first checks MARLOW’s critical sectioncount. If the count is zero, the nanokernel can immediately suspend orkill the thread on behalf of thread BACON.If MARLOW’s critical section count is non-zero, then the nanokernelmust delay its actions until MARLOW leaves the critical section.

Thenanokernel sets a flag in MARLOW’s iCsFunction member, to indicatea)That further action is requiredb)Whether the thread should suspend or exit.The nanokernel decrements the thread’s iCsCount when the threadleaves the critical section. If the thread’s iCsCount becomes zero, thenthe kernel checks the thread’s iCsFunction to see if further action isrequired.

If iCsFunction is set, then the nanokernel suspends or killsthe thread, according to the value placed in iCsFunction. Note thatthread BACON, which called Suspend() or Kill(), is not blocked atany stage – it simply carries on executing.3.2.4.2 Fast mutexesBut what of the actual mutex used to protect global data structures?Keeping the design goals for the nanokernel as a whole in mind, wederived the following requirements for a fast mutex that would efficientlyprotect short, critical sections of code:1.The mutex must be very fast in the case where there is no contentionfor the mutex2.The mutex must have a low RAM footprint3.A thread may not wait on a fast mutex if it already holds a fast mutex(fast mutexes are non-nestable)4.A thread may not block or exit while holding a fast mutex.The nanokernel then ensures that a thread is not suspended or terminatedwhile holding a fast mutex.

It does this by treating a nanothread that holdsa fast mutex as if it were in a critical section – that is, the nanokerneldelays suspending or terminating the nanothread until it releases thefast mutex.This leaves us with the case in which the thread attempts to exit whileholding a fast mutex, for example as a result of taking an exception. Inthis case, as in the one where a thread attempts to exit while in a criticalsection, the kernel will fault.If a nanothread holds a fast mutex, then, on a timeslice, the nanokernelwill not schedule another nanothread of the same priority in its place.NANOKERNEL THREADS57This is done to reduce the time spent unnecessarily switching betweenthreads in short critical sections.How fast mutexes workEach nanothread has a pointer to the fast mutex currently held bythe thread (iHeldFastMutex).

We only need one fast-mutex pointer,because, as I said earlier, we chose to design EKA2 with non-nestablefast mutexes. Naturally, the fast mutex pointer is NULL if the nanothreaddoes not hold a fast mutex.Each nanokernel thread also has a pointer to the fast mutex on whichit is currently blocked (iWaitFastMutex). Again, this pointer is NULLif the nanothread is not blocked on a fast mutex.There are two key elements in the fast mutex class. The first is a pointerto the holding thread (iHoldingThread), which is NULL if the mutexis free. The second is a flag (iWaiting), which indicates either that therewas contention for the mutex or that the nanokernel deferred an action(such as suspension, termination or round-robinning) because the mutexwas held.The algorithm for waiting on a fast mutex is:1.2.3.4.5.6.7.8.9.10.11.12.Lock the kernelIF (iHoldingThread!=NULL)iWaiting = TRUECurrent thread->iWaitFastMutex =Yield to iHoldingThread //returnLock the kernelReenable interruptsCurrent thread -> iWaitFastMutexENDIFCurrent thread -> iHeldFastMutex =iHoldingThread = Current threadUnlock the kernelthiswith ints disabled, kernel unlocked= NULLthisIf the mutex is free, this simply reduces to two variable assignments, andso is very fast.

On single-processor systems (all of them to date!), wefurther optimize this by disabling interrupts rather than locking the kernelwhen we check iHoldingThread.It is worth looking carefully at the section of pseudo code betweenthe IF and the ENDIF, lines 2 to 9. You can see that as the kernel blocks thethread, it does not remove it from the ready list. Instead, it performs theYield to iHoldingThread operation, which immediately switchesthe context to the thread that holds the mutex. We have to be careful inthe case where we are using the moving memory model (see Chapter 7,Memory Models, for more on what this means). The context switch thatwe have just done does not call the memory model hook provided toallow slow process changes, so the memory model does not get chanceto perform any page table manipulations.

We cannot allow it to do so,58THREADS, PROCESSES AND LIBRARIESbecause we want a fast mutex operation, and page table manipulationsare usually slow. This means that the kernel doesn’t guarantee a useraddress space to be consistent while the current thread holds a fastmutex. (If we are using the multiple memory model, then all is well, sincewe can perform the address space change, as in this case it is very fast.)This scheme also gives us priority inheritance on fast mutexes. Thiscomes about because the blocked thread remains on the ready list, so areschedule can only be triggered if another thread becomes ready whosepriority is at least as great as the highest priority blocked thread (seeSection 3.6).

So the holding thread can only be scheduled out by a threadwhose priority is greater than any thread already on the list – in effect itspriority is raised to that of the highest priority blocked thread.The algorithm for releasing a fast mutex is:1. Lock the kernel2.

iHoldingThread = NULL3. Current thread -> iHeldFastMutex = NULL4. IF iWaiting5. iWaiting = FALSE6. Set TheScheduler.iRescheduleNeededFlag to cause reschedule7. IF CurrentThread->iCsFunction & & CurrentThread->iCsCount==08. Do critical section exit processing for current thread9. ENDIF10. ENDIF11. Unlock the kernelIf iWaiting is NULL, then again this becomes just two variable assignments.

And again, on single-processor systems we have optimized thisby disabling interrupts rather than locking the kernel while checkingiWaiting.Remember that the nanokernel would have set the iWaiting flag ifanother nanothread had attempted to acquire the mutex while the firstnanothread held it.The nanokernel would also have set the iWaiting flag if anothernanothread had attempted to suspend or kill the first one – in this case itwould delay the function to be performed, and keep a record of whichfunction is to be performed later by storing it in iCsFunction.Finally, the nanokernel would also have set the iWaiting flag if thefirst nanothread’s timeslice had expired, because it will delay the roundrobin with other equal priority threads until the fast mutex is released.Have another look at lines 7 and 8 of the pseudo code.

They saythat the critical section exit processing will be called whenever we arenot in a critical section and there is a delayed function to be performed(iCsFunction != NULL). We can reach this point for two reasons. Thefirst is that the thread was executing in a critical section when it was killedor suspended, and now it has exited that critical section. The second isthe thread held a fast mutex when it was killed or suspended, and now ithas released the fast mutex.

The exit processing is the same in both cases.NANOKERNEL THREADS593.2.5 Nanothread deathYou can kill a nanothread by calling NThread::Kill(), but beware –this method is only intended for use by personality layers and the EPOClayer, and should not be called directly on a Symbian OS thread. This isbecause a Symbian OS thread is an extension of a nanothread, and needsto also perform its own actions on thread death, such as setting the threadexit category and the reason code.So, we believe that killing threads is not a good thing to do and itis much better to ask them nicely to stop! We have implemented thisphilosophy in the kernel process’s Symbian OS threads.

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

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

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

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