Главная » Просмотр файлов » Concepts with Symbian OS

Concepts with Symbian OS (779878), страница 17

Файл №779878 Concepts with Symbian OS (Symbian Books) 17 страницаConcepts with Symbian OS (779878) страница 172018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

So, while a thread is lightweight, itstill has an effect on a running system.On a system with restricted resources, such as a smartphone, the weightof threads has an effect. Much care is taken in restricted environmentsto be as light as possible. In these environments, processes are kept to aminimum and even threads are scrutinized as to their necessity. There istypically one main thread that controls most aspects of an application.When there are multiple threads in an application, they are usuallyspawned from the main thread and meant to deal with situations thatcause waiting, for example, network communication or device I/O, so asto free up the main thread for other functionality.It is possible to make a process – a kind of lightweight thread – thathas less of an effect; it follows a fixed kind of behavior and is lighteron a restricted system. In Symbian OS, this lightweight thread is calledan active object.

Active objects are specialized threads that have someunique characteristics.• Each active object is specifically focused on an event that causes athread or process to block: communication, device I/O, and so on.• Each active object works with a single active scheduler that listensfor events for which the object is waiting. All active objects withina process use the same scheduler; different schedulers can be usedbetween processes.• An active object defines a specific entry point in its code that is usedby the active scheduler when an event is generated. The entry point isrepresented by a standard function call that is defined for each activeobject.• While waiting for an event, all active objects within a single process,because they are maintained by the same scheduler, act as a singlethread to the system.Active objects in a single process, therefore, can be coordinated by asingle scheduler implemented in a single thread.

By combining code into74PROCESSES AND THREADSone thread that would otherwise be implemented as multiple threads,by building fixed entry points into the code, and by using a singlescheduler to coordinate their execution, active objects form an efficientand lightweight version of standard threads. See Section 4.2 for somecoding examples using active objects.Contexts and Context-switchingA process has a context, that is, the collection of system resources thatit is using represented by the process’s PCB. These resources include theregister set the process is using, the program counter, memory contentsthat implement data in its code, open files, identifying information suchas a process identifier, and so on.When a process moves to or from the running state to execute ona processor, several things must happen to the context.

The context ofthe process that preceded the current process must be extracted fromthe processor and the context of the process to be executed must beinstalled on the processor. This act of moving contexts is called a contextswitch.When switching contexts, the old context must be written to thatprocess’s PCB and the PCB must be stored. Then the PCB from the newprocess is read and restored. This procedure takes time and its efficiencyis dependent on the amount of data in the PCB and how much thehardware assists. For example, some hardware architectures provide formultiple sets of registers and switching contexts simply switches a register set without copying (this is the case, for example, on UltraSPARCarchitectures).

Context-switching incurs enough overhead that researchinto how to minimize it is worth the effort.Processes on LinuxExecution on Linux systems is organized around processes. An executingprogram on Linux is a process, characterized by a PCB and given somememory area in which to store data. In Linux, PCBs are called processdescriptors and these descriptors can be very complex.A process in Linux can be in one of the states shown in Figure 4.1.

Inaddition to these states, Linux defines two other process states: an uninterruptible state, where a process cannot be interrupted by other processesor operating system calls, and a zombie state, where a process is waitingfor a parent process to receive notification of the child’s termination. TheAN OVERVIEW OF THE PROCESS MODEL75uninterruptible state is rarely used, but is useful when a process initiatesan action that must run to completion.

For example, if a device drivertakes a long time to initialize a device, it might need to run to completionand ignore any interruption (which would cause it to lose contact withthe device it is initializing).Processes in Linux are identified by a 32-bit integer. Even thoughprocess IDs (PIDs) are stored as 32 bits, Linux maintains backwardscompatibility with older versions and only uses PIDs up to 32 767 (i.e.,the largest 16-bit integer). When PIDs reach 32 768, the system starts thenumbering process over and finds an unused PID starting at 0.In Linux, processes not only record parents and children, but alsosiblings. Relationships much like those shown in Figure 4.5 exist.

Siblingrelationships make it much easier to pass around notification of events,such as interrupts and termination events.Processes in various states in Linux are grouped together in queues.The ready queue holds the processes in the ready state that are waitingto be executed.

There are also wait queues that hold the processes inthe waiting and uninterruptible states. Processes in the zombie state donot need a queue, since there is no order to their movement out of thezombie state. Wait queues are split into subclasses of processes basedon the event for which they are waiting. Those waiting for disk I/O, forexample, are put together in their own queue separate from processeswaiting for keyboard I/O.ParentChildntre dP a h ilCP1PaC renhi tldP0SiblingP2SiblingP3ParentChildP4Figure 4.5 Process relationships in Linux76PROCESSES AND THREADSContext-switching in Linux often uses hardware to make the switchingfaster. Since Linux has been focused on the Intel hardware architecture, it takes advantage of hardware context-switching to automatically save contexts. However, using hardware to do this means thatthe operating system cannot ensure the validity of the process data.In addition, Linux has branched out from its Intel beginnings intoother hardware.

For these reasons, software context-switching usingkernel-mode procedures is implemented in the most recent versions ofLinux.One final note should be made about the process hierarchy. Everyfamily tree has a root and the Linux process hierarchy has a processwith ID 0. This process is a process started by the boot sequenceand it has the duty of initializing all operating system tables andof starting process 1, or the ‘init’ process.

The init process has thejob of starting all other processes that are needed to run a Linuxsystem.Threads in Linux follow a standard called Pthreads. Support forPthreads follows the portable operating system interface (POSIX) standardand defines an API for thread creation and synchronization.

This standardaccompanies an older standard also supported by Linux. POSIX is aset of standard APIs for system calls and was invented as a wayto smooth out the differences between Unix implementations. Mostversions of Unix and Linux adhere to the POSIX standards, as domany other operating systems. Since support is voluntary, many operating systems – including Microsoft Windows and Symbian OS – providesupport for POSIX in selected areas of API definition.

POSIX is supported by the Open Group (for more information, see their web site atwww.opengroup.org).Processes, Threads and Active Objects in Symbian OSSymbian OS favors threads and is built around the thread concept. Aprocess is seen by the operating system as a collection of threads with aPCB and memory space. Thread support in Symbian OS is based in thenanokernel with nanothreads.Recall that the nanokernel is the basic, lowest level of the kernel.It provides very simple thread support in the form of nanothreads.

Thenanokernel provides for nanothread-scheduling, synchronization (communication between threads) and timing services. Nanothreads run inprivileged mode and need a stack to store their run-time-environmentAN OVERVIEW OF THE PROCESS MODEL77data. Nanothreads do not run in user mode; this fact means that theoperating system can keep tight control over each thread. Each threadneeds a very minimal set of data to run, basically the location of itsstack and how big that stack is. The operating system keeps control ofeverything else, for example, the code each thread uses, and stores athread’s context on its run-time stack.Nanothreads have thread states in the same way as processes havestates.

The model used by the Symbian OS nanokernel adds a few states tothe basic model in Figure 4.1. In addition to the basic states, nanothreadscan be in the following states:• suspended : different from the waiting state – a thread is blocked bysome upper layer object (e.g., a Symbian OS thread)• fast Semaphore Wait : waiting for a fast semaphore – a type of sentinelvariable – to be signaled (see Chapter 6)• DFC Wait : waiting for a delayed function call (DFC) to be added tothe DFC queue; DFCs implement an interrupt service in Symbian OS,allowing a function call to be processed after the interrupt is serviced• sleeping : waiting for a specific amount of time to elapse• other : a generic state that is used when developers implement extrastates for nanothreads, to extend the nanokernel functionality fornew platforms (called personality layers); the developer must alsoimplement how states are transitioned to and from their extendedimplementations.Compare the nanothread idea with the conventional idea of a process.

A nanothread is essentially an ultra-lightweight process. It hasa mini-context that gets switched as nanothreads get moved into andout of the processor. Each nanothread has a state, as do processes.The keys to nanothreads are the tight control that the nanokernelhas over them and the minimal data that make up the context ofeach one.Symbian OS threads build upon nanothreads; the kernel adds support beyond what the nanokernel provides. User-mode threads thatfeature in standard applications are implemented by Symbian OS threads.Each Symbian OS thread contains a nanothread and adds its own runtime stack to the stack the nanothread uses.

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

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

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

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