Главная » Просмотр файлов » Smartphone Operating System

Smartphone Operating System (779883), страница 20

Файл №779883 Smartphone Operating System (Symbian Books) 20 страницаSmartphone Operating System (779883) страница 202018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Each case in the switch statement looks something likethis:case ESEr1:if (status == KErrNone){if (buffer.equals(KOk)){iSendingState = ESError; // indicate an error}else{iAppUi->SetProgress(_L("Sending the priority"));buffer.Format(KPriorityFormat, priority);Send(buffer);iSendingState = EStateXfer1;}}else{iSendingState = ESError; // indicate an erroriAppUi->SetProgress(KRcvErrMessage);}break;At the beginning of each case, we can assume that the previous I/Ooperation has completed with a value stored in a status variable. We checkthe status variable to determine if the operation completed successfully.If it was successful, we process the results, engage another I/O operation,and change the state variable for the next invocation of RunL().

If ithas not completed successfully, we must deal with it somehow – perhapsaborting the active object or resetting the communication stream. At theend of the case, if we want to continue, we must call SetActive()again.EXERCISES874.3 SummaryThis chapter discussed the concepts of working with processes andthreads in an operating system. We began the chapter by examining theprocess concept and how much of a process’s conceptual and actualimplementations are derived from the process control block.

We definedhow the operating system handles processes and how that handling hassome difficulties in implementation. We then defined threads and showedhow threads relate to and improve upon processes. User-level threadshave implications about kernel threads and we defined how these relateto each other. We also discussed the Symbian OS concept of activeobjects as special versions of threads.We discussed concepts of implementation and programming of processes, threads and active objects.

Processes use concepts of forking andjoining and we discussed how to program this type of activity in Linux.We also showed how threads can be programmed. We concluded thechapter by discussing some programming issues with active objects inSymbian OS.We have left the topic of how processes and threads are scheduled toChapter 5.Exercises1.Give examples of multithreading from the applications that you useevery day. Describe how you think each example would work if asingle thread of control were to be used.2.Consider situations where multithreaded applications would not bemore useful than singlethreaded applications.

Describe two examplesof this and give your explanation as to why there is no performanceimprovement.3.Give two situations where kernel multithreading would definitely bean improvement over singlethreading.4.Give two situations where kernel multithreading would not be animprovement over singlethreading.5.Compare context-switching between user-level threads with contextswitching between kernel-level threads. Where are they the same?Where are they different?88PROCESSES AND THREADS6.Consider how a process is created. Compare the procedure with howa thread is created.

How are resources used differently?7.Compare the creation of active objects with the creation of threads.How do you think these procedures are different?8.Give two situations where active objects would not be better thanthreading. Explain your thinking.5Process SchedulingWe introduced the last chapter with a circus performer: a man that Iremember from childhood who kept plates spinning on sticks. He couldspin many plates at the same time. While his performance seemed to befocused on the spinning plates, I suspect that his real skill lay in the choicehe made after he paid attention to a single plate.

In the split second wherehe ran from one plate to another, keeping each spinning on those longsticks, he had to make a choice as to the plate that needed his attentionmost. If he chose poorly, at least one plate would begin to wobble andeventually fall off its stick and break. If he chose wisely, he kept all theplates spinning.We can think of this circus performer as a scheduler. He needs tomake important choices that schedule plates for ‘spin maintenance’.Some plates probably need his attention more than others and he needsto make his choices wisely, according to the needs of the plates.Computer operating systems are like that.

They have a limited set ofCPUs (usually only one) that are to be used by many processes at once.As the operating system shares the computing resources, choices mustbe made. How long should a process operate on a CPU? Which processshould run next? How often do we check the system?The concept of scheduling a CPU is very important to keeping acomputer running quickly and efficiently. This chapter introduces thebasic ideas of CPU scheduling and presents several scheduling algorithms.We also examine how these concepts and algorithms apply to varioustypes of operating system architectures.90PROCESS SCHEDULING5.1 Basic ConceptsThe concepts involved with scheduling a CPU seem simple on theoutside but are really quite difficult upon closer inspection.

The ideaof multiprogramming is essentially a simple one: several processes shareprocessing time on a CPU. The idea of sharing is an easy concept to grasp.However, it is the mechanics of this sharing that is difficult. Processesmust be started appropriately and stopped at the right time, allowinganother process to take over the CPU. What is appropriate? How longdoes the process have the CPU? What is the next process to take over?These questions make sharing a difficult concept indeed.Concepts of SharingWe need to be clear on how the CPU is shared. The act of schedulingis the act of moving processes from the ready state to the running stateand back again.

Recall that processes in the ready state are waiting in theready queue. This ready queue is not necessarily a FIFO queue: processesdo not necessarily enter and leave in a fixed order. In fact the choice ofwhich process to move from the ready queue to running is at the heart ofprocess scheduling.The way CPU sharing is controlled is important. Methods of sharing should accommodate the way that a process works. For example,we could allow processes to share a processor at their own discretion.

This would mean that sharing would be dependent on eachprocess – dependent on when each process decided to give up theprocessor. This makes it easy for a process to hog the CPU and notgive it up. Obviously, this makes the operating system a bit simpler,but would not be a great way to equitably share things on a generalpurpose computer.

We could also move scheduling decisions away fromeach process and give them to a third party – perhaps the operatingsystem. This would make scheduling less dependent on the whim ofeach process and more dependent on policies implemented by a centralcontroller.When a process moves from the running state to the ready statewithout outside intervention, we call the scheduling mechanism a nonpre-emptive mechanism.

Many movements from the running state arenon-pre-emptive. When a process moves to the waiting state or a processterminates, it does so by its own choice. In non-pre-emptive scheduling,a process may hang on to the CPU for as long as it wants (or needs) to.BASIC CONCEPTS91By contrast, pre-emptive scheduling allows the operating system tointerrupt a process and move it between states. Pre-emptive scheduling is usually used for general-purpose operating systems because themechanism used can be fairer and processes can be simpler. However,pre-emptive scheduling can have costs associated with it.

It requires morehardware support: timers must be implemented to support the timing criteria for processes and ways of switching between processes must besupported by registers and memory. The operating system must also provide secure ways of sharing information between processes. Consider twoprocesses sharing data between them.

If one is pre-empted as it is writingdata and the second process is then run on the CPU, it might beginto read corrupted data that the first process did not completely write.Mechanisms must be in place that allow the processes to communicatewith each other to indicate that such conditions exist.Pre-emptive scheduling affects how the operating system is designed.The kernel must be designed to handle interrupts for a context switch atany time – even the most inopportune times. For example, if a processmakes a system call that causes the kernel to make system changes butit is pre-empted, what happens to the changes made by the kernel? Thisis complicated by the chance that the next process might depend onthe changes made by the previous process’s system call.

Corruption ofsystem data is likely if this is not handled correctly. In a case like this, aLinux system would force the context switch to wait until the kernel modechanges were completed or an I/O call is made. This method ensures thatprocesses sharing one CPU serialize access to system resources. Even thisway of coordinating access to system resources is not sufficient when thereare multiple CPUs or the operating system supports real-time processing.Most modern operating systems use pre-emptive schedulers but thereare several examples of non-pre-emptive kernels.

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

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

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

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