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

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

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

Instead we mark the current thread as preempted, leaveit suspended, and signal another dedicated interrupt-rescheduler threadto do the reschedule on behalf of the preempted thread. This interruptrescheduler thread is a nanokernel thread that spends its entire life insideTScheduler::Reschedule() – it is not on the ready list and so thenanokernel never selects it to be run, but EndOfInterrupt() can wakeit up when necessary to schedule the next thread.When the nanokernel selects a preempted thread to run rather thansignaling the reschedule lock, the emulator must resume the host thread.However, life is not that simple – there’s more to do.

On a phone, whenthe nanokernel schedules a thread, the kernel is locked. The kernel thenmakes a final check of the iDfcPending and iRescheduleNeeded112THREADS, PROCESSES AND LIBRARIESflags before unlocking and resuming where it left off. In the emulator, if wemerely resume the preempted thread, then we will just do the final itemin that list, and miss out the checks. This means that the current threadmust do the checks (restarting the reschedule if required) and unlock thekernel on behalf of the preempted thread. This makes the handover to apreempted thread rather more complex than it is on the mobile phone.The beauty of this method is that no side effects are apparent to users ofthe emulator.

The Win32 version of the nanokernel has some pretty trickycode in it, but this ensures that the rest of the kernel just works – becauseit presents the same model as on real hardware.3.6.2.4 IdlingIn the emulator, there is no way to ‘‘idle the CPU’’ from the Symbian OSnull (idle) thread and the obvious alternative – going round in an infiniteloop – is not very nice to the PC!The null thread calls NThread::Idle() to go into idle mode on boththe emulator and a phone. On the emulator, this sets a flag to indicatethat the emulator is idle, and then waits on the thread’s reschedule lock.The EndOfInterrupt() function detects this state as a special caseand instead of using the interrupt-rescheduler thread, it just wakes up thenull thread.

The null thread then reschedules. Next time the null threadis scheduled, it returns from NThread::Idle() and so behaves in asimilar fashion to its counterpart on real phones.3.7 Dynamically loaded librariesI have talked about threads and processes; I will finish this chapter witha short discussion on dynamically loaded libraries, or DLLs. You can findmore on this subject in Chapter 8, Platform Security and Chapter 10, TheLoader.3.7.1 The DLibrary classThe kernel creates a kernel-side library object (DLibrary) for every DLLthat is explicitly loaded into a user process; that is, one that is the targetof an RLibrary::Load() rather than one that is implicitly linked toby another executable.

Library objects are specific to, and owned by, theprocess for which they were created; if two processes both load the sameDLL, the kernel creates two separate DLibrary objects. A library hastwo main uses:1.It represents a link from a process to the global code graph. Eachprocess always has at least one such connection – the DProcess::iCodeSeg pointer. This pointer, set up by the kernel atDYNAMICALLY LOADED LIBRARIES113process load time, links each process to its own EXE code segment.DLibrary objects represent additional links to the code graph,created at run time.2.

It provides a state machine to ensure that constructors and destructorsfor objects resident in .data and .bss sections are called correctly.Libraries have two reference counts. One is the standard DObjectreference count (since DLibrary derives from DObject); a non-zerovalue for this reference count simply stops the DLibrary itself beingdeleted – it does not stop the underlying code segment being deleted orremoved from any process.The second reference count (iMapCount) is the number of userreferences on the library, which is equal to the number of handles on thelibrary opened by the process or by any of its threads.

The kernel alwaysupdates this count with the CodeSegLock mutex held. When the lastuser handle is closed, iMapCount will reach zero and this triggers thecalling of static destructors and the removal of the library code segmentfrom the process address space.The loader creates DLibrary objects on behalf of a client loading aDLL. A process may not have more than one DLibrary referring to thesame code segment. If a process loads the same library twice, the kernelwill open a second handle for it on the already existing DLibrary andits map count will be incremented.A DLibrary object transitions through the following states duringits life:• ECreated – transient state in which object is created.

Switches toELoaded or EAttached when library and corresponding code segment are added to the target process• ELoaded – code segment is loaded and attached to the target processbut the kernel has not called static constructors• EAttaching – the target process is currently running the code segment static constructors. Transitions to EAttached when constructorshave completed• EAttached – static constructors have completed and the code segment is fully available for use by the target process• EDetachPending – the last user handle has been closed on theDLibrary but static destructors have not yet been called. Transitionsto EDetaching just before running static destructors• EDetaching – the target process is currently running the code segment static destructors. Transitions to ELoaded when destructorshave completed.114THREADS, PROCESSES AND LIBRARIESLet’s have a look at the Dlibrary class:class DLibrary : public DObject{public:enum TState{ECreated=0,// initial stateELoaded=1,// code segment loadedEAttaching=2,// calling constructorsEAttached=3,// all constructors doneEDetachPending=4, // about to call destructorsEDetaching=5,// calling destructors};public:static TInt New(DLibrary*& aLib, DProcess* aProcess,DCodeSeg* aSeg);DLibrary();void RemoveFromProcess();virtual ∼DLibrary();virtual TInt Close(TAny* aPtr);virtual TInt AddToProcess(DProcess* aProcess);virtual void DoAppendName(TDes& aName);public:TInt iMapCount;TUint8 iState;SDblQueLink iThreadLink; // attaches to opening/closing threadDCodeSeg* iCodeSeg;};Key member data of DLibraryiMapCountCount of the number of times this library is mapped into the process;equal to the number of user handles the process and its threads have onthis library.iStateRecords progress in calling user-side constructors or destructors duringlibrary loading and unloading.iThreadLinkDoubly linked list field, which is used to attach the library to the threadthat is running user-side constructors or destructors.

This is needed toenable cleanup if the thread terminates while running one of thesefunctions.iCodeSegPointer to the code segment to which this library refers.3.7.2 Code segmentsI mentioned that a library represents a link from a process to the globalcode graph, and that this link is held in the iCodeSeg pointer. Thispointer denotes a kernel object known as a DCodeSeg.SUMMARY115A DCodeSeg is an object that represents the contents of an executable,relocated for particular code and data addresses. Executable programs(EXEs) or dynamically loaded libraries (DLLs), execute in place (XIP) orRAM-loaded – whatever the combination, the code is represented by aDCodeSeg.On EKA1, EXEs and DLLs were handled separately and differently,which gave us problems when we came to load a DLL that linked backto an EXE.Under EKA2, the unification of the support for loading code under theDCodeSeg has made matters much simpler. Multiple instances of thesame process will use the same DCodeSeg unless a RAM-loaded fixedprocess needs different data addresses.

Similarly, if a DLL is loaded intoseveral processes, the same DCodeSeg is attached to all the processes(the code is shared), unless different data addresses are required. Thishappens when a RAM-loaded DLL with writable static data is then loadedinto more than one fixed process, or into a combination of fixed andnon-fixed processes.I will discuss this in greater depth in Chapter 10, The Loader.3.8 SummaryIn this chapter I have talked about threads in the nanokernel, and SymbianOS threads, processes and libraries. Of course, these are fundamentaloperating system concepts, and you will find that they form an importantbasis for other parts of this book.In the next chapter, I shall talk about some of the ways in whichthreads and processes can communicate with each other.4Inter-thread Communicationby Andrew Rogers and Jane SalesBe not deceived: evil communications corrupt good manners.1 Corinthians 15:33In the last chapter, I introduced Symbian OS threads.

Now I will goon to discuss some of the mechanisms that those threads can use tocommunicate with one another.Symbian OS provides several such mechanisms, including shared I/Obuffers, publish and subscribe, message queues and client-server. Each ofthe methods has its particular merits and restrictions. I will examine eachof them in turn, discussing their implementation and the general class ofproblem each is intended to solve.

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

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

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

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