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

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

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

But this presents us witha problem: if we release the highest-priority thread and it is killed beforeit has had chance to acquire the mutex, then the mutex remains free butnone of the waiting threads can claim it – because they are all blocked.The solution is simply that the kernel moves the next highest-prioritythread from the EWaitMutex state to EHoldMutexPending.The thread that holds the mutex is in the EReady state.

It is linkedto the mutex by way of its cleanup queue and each mutex has aTThreadCleanup object embedded in it. When a thread acquires themutex, the kernel adds the TThreadCleanup object to the thread’scleanup queue. (While the mutex remains free, the cleanup item is notlinked to any queue and its cleanup item’s thread pointer is NULL.) Thepriority of the cleanup item is equal to that of the highest-priority threadon the mutex wait queue. The kernel first sets this priority when a threadacquires the mutex, just before adding the cleanup item to the thread’scleanup queue.

If another thread subsequently waits for the mutex thenthe kernel adjusts the priority of the cleanup item (if the new waitingthread has a higher priority than any other). Raising the cleanup item’spriority may then cause the holding thread’s priority to increase (if thenew cleanup priority is higher than the holding thread’s default priority).In this way, the holding thread’s priority will never be less than that ofany waiting thread, and so we get priority inheritance.What happens if the holding thread is itself blocked on another mutex?In this case the kernel may elevate the priority of the holding thread ofthe second mutex if necessary. In principle, a sequence like this maybe arbitrarily long, which would result in an arbitrarily long executiontime for the mutex wait operation.

To avoid this, we terminate the chainonce we have traversed 10 mutexes. Priority inheritance will no longeroperate if a chain of mutexes exceeds this length.SYMBIAN OS THREADS83To ensure that the highest-priority thread always acquires the mutexfirst, the kernel must take action whenever a thread performs any of thefollowing operations on a thread associated with the mutex:• Suspends• Resumes• Kills• Changes priority.The following table summarizes the required actions. (The row indicatesthe relationship of the thread to the mutex, the column indicates theoperation performed on the thread.)SuspendResumeKillPriority changeHolding threadNo action.No action.Signal mutex.Priority of threadwill not dropbelow that ofhighest-prioritywaiting thread.WaitingChange threadstate towait/suspend.Adjust cleanuppriority.Not applicable.Remove from wait If priority raisedqueue and adjust and mutex free,cleanup priority.make threadpending.

If mutexnot free adjustcleanup priority.If mutex free makethread pendingelse make threadwaiting and adjustcleanup priority.Remove fromsuspended queueand adjustcleanup priority.No action.Remove threadfrom pendingqueue. If mutexfree and waitqueue non-empty,make highestpriority waitingthread pending.If mutex free andthread priorityreduced below thatof highest-prioritywaiting thread,make the latterpending.Waiting/suspended No action.PendingIf mutex free and No action.wait queuenon-empty,makehighest-prioritywaiting threadpending.The kernel and memory model use DMutex extensively to protectglobal data structures that are accessed by multiple threads. The kernelprotects DMutex operations using the system lock fast mutex.Note that DMutex operations rely on fields that are present in DThreadbut not in NThread.

Hence only Symbian OS threads may invoke mutex84THREADS, PROCESSES AND LIBRARIESoperations; it is not permitted for an IDFC or a non-Symbian OS threadto use a Symbian OS mutex.We represent a Symbian OS mutex by the DMutex class. Like manyothers, this class is derived from DObject, which makes it a dynamicallyallocated reference counted object. DMutex is the kernel object referredto by a user-side RMutex handle:class DMutex : public DObject{public:TInt Create(DObject* aOwner, const TDesC* aName,TBool aVisible, TUint aOrder);public:DMutex();∼DMutex();TInt HighestWaitingPriority();void WaitCancel(DThread* aThread);void WaitCancelSuspended(DThread* aThread);void SuspendWaitingThread(DThread* aThread);void ResumeWaitingThread(DThread* aThread);void ChangeWaitingThreadPriority(DThread* aThread,TInt aNewPriority);void SuspendPendingThread(DThread* aThread);void RemovePendingThread(DThread* aThread);void ChangePendingThreadPriority(DThread* aThread,TInt aNewPriority);void WakeUpNextThread();public:TInt Wait();void Signal();void Reset();public:TInt iHoldCount;TInt iWaitCount;TUint8 iResetting;TUint8 iOrder;TUint8 iPad1;TUint8 iPad2;TThreadMutexCleanup iCleanup;SDblQue iSuspendedQ;SDblQue iPendingQ;TThreadWaitList iWaitQ;#ifdef _DEBUGSDblQueLink iORderLink;#endifpublic:friend class Monitor;};Key member data of DMutexiHoldCountCount of the number of times the holding thread has waited on this mutexin a nested fashion.

We increment this field if the holding thread waitsSYMBIAN OS THREADS85again and decrement it if it signals the mutex; in the latter case we releasethe mutex if iHoldCount becomes zero.iWaitCountCount of the number of waiting threads plus the number of waiting andsuspended threads. This is used only to implement theRMutex::Count() method.iResettingThis flag is set while the mutex is being reset; this occurs just prior to themutex being deleted and involves releasing and unlinking any waiting,suspended or pending threads.

The flag is used to prevent further threadswaiting on the mutex.iCleanupA TThreadCleanup entry used both to enable the mutex to be releasedif the holding thread exits and also to enable the holding thread toinherit the priority of the highest-priority waiting thread. The iThreadmember of iCleanup is a pointer to the holding thread; a NULL valuefor iCleanup.iThread indicates that the mutex is free.iSuspendedQA doubly linked list of threads that are both waiting on the mutex andexplicitly suspended.

These threads have iWaitObj pointing to thismutex and have M-state EWaitMutexSuspended.iPendingQA doubly linked list of threads, released by the kernel after waiting ona mutex, but which have not yet claimed that mutex. These threadshave iWaitObj pointing to this mutex and have M-state EHoldMutexPending.iWaitQA 64-priority list of threads that are waiting on the mutex and that arenot explicitly suspended. These threads have iWaitObj pointing to themutex and have M-state EWaitMutex.3.3.7.3 Condition variables – DCondVarOften, a thread will need to block until some data that it shares with otherthreads reaches a particular value. In Symbian OS, it can do this by usinga POSIX-style condition variable.Condition variables provide a different type of synchronization tolocking mechanisms like mutexes.

Mutexes are used to make otherthreads wait while the thread holding the mutex executes code in a criticalsection. In contrast, a thread uses a condition variable to make itself waituntil an expression involving shared data attains a particular state.86THREADS, PROCESSES AND LIBRARIESThe kernel-side object is DCondVar, and its class definition is shownin the first of the two code samples which follow. Access to DCondVarfrom user-side is via RCondVar, which is shown in the second sample.Condition variables are always used in association with a mutex toprotect the shared data. In Symbian OS, this is, of course, an RMutexobject.DCondVarclass DCondVar : public DObject{public:TInt Create(DObject* aOwner, const TDesC* aName, TBool aVisible);public:DCondVar();∼DCondVar();void WaitCancel(DThread* aThread);void WaitCancelSuspended(DThread* aThread);void SuspendWaitingThread(DThread* aThread);void ResumeWaitingThread(DThread* aThread);void ChangeWaitingThreadPriority(DThread* aThread, TIntaNewPriority);public:TInt Wait(DMutex* aMutex, TInt aTimeout);void Signal();void Broadcast(DMutex* aMutex);void Reset();void UnBlockThread(DThread* aThread, TBool aUnlock);public:TUint8 iResetting;TUint8 iPad1;TUint8 iPad2;TUint8 iPad3;DMutex* iMutex;TInt iWaitCount;SDblQue iSuspendedQ;TThreadWaitList iWaitQ;public:friend class Monitor;};RCondVarclass RCondVar : public RHandleBase{public:IMPORT_C TInt CreateLocal(TOwnerType aType=EOwnerProcess);IMPORT_C TInt CreateGlobal(const TDesC& aName,TOwnerType aType=EOwnerProcess);IMPORT_C TInt OpenGlobal(const TDesC& aName,TOwnerType aType=EOwnerProcess);IMPORT_C TInt Open(RMessagePtr2 aMessage, TInt aParam,TOwnerType aType=EOwnerProcess);IMPORT_C TInt Open(TInt aArgumentIndex,TOwnerType aType=EOwnerProcess);SYMBIAN OS THREADSIMPORT_CIMPORT_CIMPORT_CIMPORT_C};TIntTIntvoidvoid87Wait(RMutex& aMutex);TimedWait(RMutex& aMutex, TInt aTimeout);Signal();Broadcast();You can see that the condition to be tested lives outside of the conditionvariable.

This is because the condition is application-defined, and allowsit to be as complex as you wish. The only real requirement is that thevolatile data being tested by the condition is protected by the mutex thatis being used with the condition variable.Let’s look at how condition variables are used in practice.One common use case for condition variables is the implemention ofthread-safe message queues, providing a producer/consumer communication mechanism for passing messages between multiple threads.

Herewe want to block producer threads when the message queue is full andwe want to block consumer threads when the queue is empty. Assumethat the queue is a doubly linked list of messages. Clearly we will needto protect this list with a mutex (let’s call it myMutex), so that producersand consumers do not interfere with each other as they add and removemessages from the queue.Now let’s look at this from the point of view of the consumer thread,and let’s suppose that there are no messages for it to process.

Howdoes it deal with this situation? The consumer thread could repeatedlylock and unlock myMutex, each time checking the linked list for moremessages. But this busy polling is extremely inefficient. It is far betterfor the consumer thread to first wait on myMutex, and then on thecondition variable, by calling RCondVar::Wait(RMutex&aMutex).This method will only return when there is a new message on the list.What goes on behind the scenes when this happens?The consumer thread ends up in DCondVar::Wait(). This is kernelcode, but it is running in the consumer thread’s context.

Almost the firstthing DCondVar::Wait() does is to release the mutex. The functionthen blocks – this means the consumer thread does not run again untilthe condition variable is signaled. Now that myMutex is unlocked, otherthreads that were blocked on the mutex may become runnable, and canaccess and modify the message-status variable.Suppose a producer thread signals the condition variable. What thenhappens to our sleeping consumer thread? Immediately after it wakes,still in DCondVar::Wait(), it re-aquires the mutex, preventing accessby other threads and making it safe for it to examine the shared data itself.So we have seen that usage pattern for condition variables is as follows:mutex.Wait();while(!CONDITION)88THREADS, PROCESSES AND LIBRARIES// possible race condition here if signalling thread// does not hold mutexcondvar.Wait(mutex);STATEMENTS;mutex.Signal();Here CONDITION is an arbitrary condition involving any number ofuser-side variables whose integrity is protected by the mutex.

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

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

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

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