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

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

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

ForSymbian OS threads, it serves as the Symbian OS request semaphore.iSuspendCountInteger, ≤0, which equals minus the number of times a thread has beenexplicitly suspended.iCsCountInteger, ≥0, which indicates whether the thread may currently be killed orsuspended. These actions can only happen if this count is zero, otherwisethey are deferred.iCsFunctionInteger that indicates what if any action was deferred due to iCsCountbeing non-zero.

If zero, no action is required; if positive, it equals thenumber of explicit suspensions that have been deferred; if negative, itindicates that a thread exit has been deferred.50THREADS, PROCESSES AND LIBRARIESiTimerNanokernel timer object used to sleep the thread for a specified time andto implement wait-for-event-with-timeout functions.iExitHandlerPointer to function. If it is not NULL the kernel will call the function whenthis thread exits, in the context of the exiting thread.iStateHandlerPointer to function that is called if the thread is suspended, resumed,released from waiting or has its priority changed and the iNState is nota standard nanokernel thread state.

Used to implement RTOS emulationlayers.iExceptionHandlerPointer to function called if the thread takes an exception. On ARM, thefunction is called if a prefetch abort, data abort or undefined instructiontrap occurs. The function is always executed in mode_svc1 in the contextof the current thread, regardless of the exception type.iFastExecTablePointer to table of fast executive calls for this thread.iSlowExecTablePointer to table of slow executive calls for this thread – see Section 5.2.1.7for details.3.2.2 Nanothread creationThe nanokernel provides the static API below to allow kernel modulesoutside of the nanokernel to create a nanothread:NKern::ThreadCreate(NThread* aThread, SNThreadCreateInfo& aInfo)This function takes an SNThreadCreateInfo structure as a parameter.The caller also passes a pointer to a new NThread object, which ithas instantiated beforehand.

This must be done because the nanokernelcannot allocate or free memory.3.2.2.1 SNThreadCreateInfoThe SNThreadCreateInfo structure looks like this:struct SNThreadCreateInfo{1An ARM CPU mode that is associated with a different register set. See Chapter 6,Interrupts and Exceptions, for more on this.NANOKERNEL THREADS51NThreadFunction iFunction;TAny* iStackBase;TInt iStackSize;TInt iPriority;TInt iTimeslice;TUint8 iAttributes;const SNThreadHandlers* iHandlers;const SFastExecTable* iFastExecTable;const SSlowExecTable* iSlowExecTable;const TUint32* iParameterBlock;TInt iParameterBlockSize;// if 0,iParameterBlock is initial data// otherwise it points to n bytes of initial data};Key member data of SNThreadCreateInfoiFunctionAddress of code to execute.iStackBaseBase of stack for new NThread.

This must be preallocated by thecaller – the nanokernel does not allocate it.iHandlersPoints to the handlers for different situations, namely:• iExitHandler: called when a thread terminates execution• iStateHandler: called to handle state changes when the iNStateis not recognized by the nanokernel (used so OS personality layerscan implement new NThread states)• iExceptionHandler: called to handle an exception• iTimeoutHandler: called when the NThread::iTimer timerexpires.3.2.2.2 SNThreadHandlersThe SNThreadHandlers structure looks like this:struct SNThreadHandlers{NThreadExitHandler iExitHandler;NThreadStateHandler iStateHandler;NThreadExceptionHandler iExceptionHandler;NThreadTimeoutHandler iTimeoutHandler;};Key member data of SNThreadCreateInfoiParameterBlockEither a pointer to a block of parameters for the thread, or a single 32-bitparameter.52THREADS, PROCESSES AND LIBRARIESiParameterBlockSizeIf zero, iParameterBlock is a single 32-bit parameter.

If non-zero, itis a pointer.iFastExecTableAllows personality layer to pass in a pointer to a table of exec calls to beused for this thread.iSlowExecTableAllows personality layer to pass in a pointer to a table of exec calls to beused for this thread.3.2.2.3 Creating a nanothreadReturning to NKern::ThreadCreate(), you can see that the callerpasses in the address of the stack that the nanothread will use. This isbecause the nanokernel cannot allocate memory – so anyone creating ananothread must first allocate a stack for it.NThread::Create()TInt NThread::Create(SNThreadCreateInfo& aInfo, TBool aInitial){TInt r=NThreadBase::Create(aInfo,aInitial);if (r!=KErrNone)return r;if (!aInitial){TUint32* sp=(TUint32*)(iStackBase+iStackSizeaInfo.iParameterBlockSize);TUint32 r6=(TUint32)aInfo.iParameterBlock;if (aInfo.iParameterBlockSize){wordmove (sp,aInfo.iParameterBlock,aInfo.iParameterBlockSize);r6=(TUint32)sp;}*--sp=(TUint32)__StartThread;// PC*--sp=0;// R11*--sp=0;// R10*--sp=0;// R9*--sp=0;// R8*--sp=0;// R7*--sp=r6;// R6*--sp=(TUint32)aInfo.iFunction;// R5*--sp=(TUint32)this;// R4*--sp=0x13;// SPSR_SVC*--sp=0;// R14_USR*--sp=0;// R13_USRiSavedSP=(TLinAddr)sp;}NANOKERNEL THREADS53NThreadBase::Create()TInt NThreadBase::Create(SNThreadCreateInfo& aInfo, TBool aInitial){if (aInfo.iPriority<0 || aInfo.iPriority>63)return KErrArgument;new (this) NThreadBase;iStackBase=(TLinAddr)aInfo.iStackBase;iStackSize=aInfo.iStackSize;iTimeslice=(aInfo.iTimeslice>0)?aInfo.iTimeslice:-1;iTime=iTimeslice;iPriority=TUint8(aInfo.iPriority);iHandlers = aInfo.iHandlers ? aInfo.iHandlers :&NThread_Default_Handlers;iFastExecTable=aInfo.iFastExecTable?aInfo.iFastExecTable:&DefaultFastExecTable;iSlowExecTable=(aInfo.iSlowExecTable?aInfo.iSlowExecTable:&DefaultSlowExecTable)->iEntries;iSpare2=(TUint8)aInfo.iAttributes;// iSpare2 is NThread attributesif (aInitial){iNState=EReady;iSuspendCount=0;TheScheduler.Add(this);TheScheduler.iCurrentThread=this;TheScheduler.iKernCSLocked=0;// now that current thread is defined}else{iNState=ESuspended;iSuspendCount=-1;}return KErrNone;}The static function NKern::ThreadCreate() merely callsNThread::Create() (the first code sample), which then callsNThreadBase::Create()(the second sample).

This function sets upvarious properties of the new thread, including:• its stack• its priority• its timeslice• its slow and fast exec tables.NThreadBase::Create() then puts the new nanothread into thesuspended state and returns.NThread::Create() sets up a stack frame for the new nanothread,first copying over the parameter block (if any) and then creating register54THREADS, PROCESSES AND LIBRARIESvalues, ready for the thread to pop them. The kernel gives the thread’sprogram counter register (on the stack) the value of __StartThread(see the following code sample). To find out more about where in memorywe create the thread’s stack, see Chapter 7, Memory Models.__StartThread__NAKED__ void __StartThread(){// On entry r4->current thread, r5->entry point, r6->parameter blockasm("mov r0, r6 ");asm("mov lr, pc ");asm("movs pc, r5 ");asm("b " CSM_ZN5NKern4ExitEv);}__StartThread merely assigns some registers, so that iFunctionis called with the iParameterBlock function as its argument.

IfiFunction returns, __StartThread branches to Kern::Exit toterminate the thread.3.2.3 Nanothread lifecycle3.2.3.1 Nanothread statesA nanokernel thread can be in one of several states, enumerated byNThreadState and determined by the NThread ’s iNState memberdata. I will describe these states below:iNState==EReadyThreads in this state are eligible for execution. They are linked into theready list.

The highest priority EReady thread is the one that will actuallyexecute at any given time, unless it is blocked on a fast mutex.iNState==ESuspendedA thread in this state has been explicitly suspended by another threadrather than blocking on a wait object.iNState==EWaitFastSemaphoreA thread in this state is blocked waiting for a fast semaphore to be signaled.iNState==EWaitDfcThe thread is a DFC-handling thread and it is blocked waiting for a DFCto be added to the DFC queue that it is servicing. (For more on DFCs, seeSection 6.3.2.3.)iNState==ESleepA thread in this state is blocked waiting for a specific time period to elapse.NANOKERNEL THREADS55iNState==EBlockedThe thread is blocked on a wait object implemented in a layer abovethe nanokernel. This generally means it is blocked on a Symbian OSsemaphore or mutex.iNState=EDeadA thread in this state has terminated and will not execute again.iNState=otherIf you are writing a personality layer (see Chapter 17, Real Time) then youmay choose to allow your nanothreads to have extra states; that is youriNState will be able to take a value other than those above.

You mustthen provide an iStateHandler in your NThread, and then the kernelwill call this function if there is a transition in state for this nanothread – ifit is resumed, blocked and so on.3.2.4 Mutual exclusion of nanothreads3.2.4.1 Critical sectionsA critical section is any sequence of code for which a thread, once it hasentered the section, must be allowed to complete it. In other words, thenanokernel must not suspend or kill a thread that is in a critical section.The nanokernel has sections of code that update kernel global data,and where preemption is enabled.

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

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

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

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