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

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

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

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

Such multithreaded processes havepotential for executing faster than processes with a single thread.Not all components of a process are shared. Threads do have somecomponents they keep private (see Figure 4.3). For multiple threads tohave their own execution space, each thread must command its ownprogram counter and its own set of registers. Each thread becomes anentity that can be scheduled and has a set of interrupts that it responds to.Multithreading communicationsLet’s say that you are using the Internet and begin to browse someweb pages.

Your browser program executes on your behalf by starting aprocess and moving that process through process states until it begins toshare the CPU with the other processes on the system. You type a URLinto the ‘Address’ field in the browser and click the ‘Go’ button. You nowexpect your browser to go and fetch a web page from the Internet anddisplay it.68PROCESSES AND THREADSFile SpaceInput/OutputFile SpaceRegistersProgram StackFigure 4.3RegistersRegistersRegistersRegistersProgramStackProgramStackProgramStackProgramStackThread #4Input/OutputThread #3Data SegmentThread #2Code SegmentThread #1Data SegmentSingle ThreadCode SegmentSinglethreaded and multithreaded processesConsider what would happen at this point if your browser used a singlethread of control.

The browser interface would freeze while the processfetched and displayed the web page you requested. In fact, because webpages often result in many files to be fetched (for example, image and textfiles), the page would render quite slowly, because only one file wouldbe fetched, then rendered, at a time.Most web browser implementations are multithreaded.

You candemonstrate this for yourself. Try viewing a complex website – onewith many graphics – and use the menu system on your browser. Trydownloading a web page then download it again when the first time isonly halfway through. Even simple things show multithreading: roll yourmouse over a link in a web page while it is downloading and you willusually see the cursor change. All of these activities would not be possiblewithout a multithreaded implementation.Consider the web server that answers the requests that web browsersmake for web pages.

If a web server used only a single thread, only oneweb page request would be serviced at a time. Requestors would haveto wait a long time while the components of a single web page weredelivered.After considering these illustrations, you might think that multiplethreads are the best way to program in applications. This is usually true.AN OVERVIEW OF THE PROCESS MODEL69However, there are times when a single thread is more beneficial.

This isusually the case when a resource, such as a device or special sections ofmemory, is shared but must be accessed carefully – usually by one threadat a time. To do otherwise would corrupt the resource or the data derivedfrom it. We discuss concurrency in operating systems more in Chapter 6.Benefits of multithreadingProcesses benefit from multithreading in a number of ways:• Sharing of resources : threads share the memory space, the operatingsystem resources and even the code of the process to which theybelong.• Saving resources : because threads share resources amongst themselves and with the process that spawned them, expensive andtime-consuming allocation of new resources is not required for eachthread; threads often require the same kind of attention that processesdo but they require fewer resources which makes operations such ascreating and scheduling a thread much faster.• Interacting with users : multithreaded applications can interact withusers while doing other things; if there are operations that requirewaiting or computing for a long period of time, multiple threads allowan application to attend to these long operations while still makingthe user feel as if she is in control.

Because multiple operations canbe going on at the same time, applications feel quicker and moreresponsive.• Accessing multiple processors : if a computing system has multipleprocessors, multithreaded application can take advantage of this;multiple threads, like multiple processes, can each be scheduled torun on a separate processor. True parallelism can be achieved whenseparate threads of a single application run on separate processors.User and kernel threadsWhen an application is multithreaded, it is composed of user threads.These threads run on behalf of an application, which is itself runningat the user level. Threads that run on behalf of users at the user levelconsume user resources and interact with the system at the user level.The kernel is not needed until system calls are made.70PROCESSES AND THREADS(a)Figure 4.4 Kernel thread models(c)kernel threaduser threadkernel threaduser threadkernel threaduser threadkernel threaduser thread(b)user threadkernel threadkernel threaduser threaduser threadkernel threaduser threaduser threaduser threaduser threaduser threadkernel threadIf an operating system supports user-level multithreading, the threadingof the kernel affects how multithreaded applications execute.

As ananalogy, consider a multilane highway that merges to a single lane as itgoes through a small town. When the highway is busy, merging all thoselanes of traffic onto the single road causes huge backups as cars in eachlane wait their turn to enter the single road.In a similar manner, some kernels that support multithreading at theuser level support only a single thread at the kernel level. This is calleda many-to-one model of kernel threading (see Figure 4.4a). Many userthreads compete for a single thread of kernel control.

As with the highwayexample, the result is a backlog of kernel requests and much waiting onbehalf of user threads.In a many-to-one system, applications still get some user-level benefitfrom multithreading but when they interact with the kernel there is noAN OVERVIEW OF THE PROCESS MODEL71additional benefit. In fact, many systems that use singlethreaded kernels(for example, Microsoft Windows NT) restrict the number of user threadsthat can be used at any one time.

Note that, in this model, a single threadcan block an application. If multiple threads need the kernel, only onegets through and the rest block.An alternative to a many-to-one model is a model where the kernelspawns a new thread for each user thread that makes a kernel-level request(see Figure 4.4b). This is called a one-to-one model of kernel threading.Each kernel thread services the requests from a single user thread. Thisincreases concurrency and eliminates the backlog of requests. In the oneto-one model, each thread in an application could be serviced, whichmeans an application does not block when a single thread needs kernelservices.

In this model, threads are created and destroyed based on therequests that come in. The overhead of creating kernel threads can startto affect the performance of applications. If an application requires manykernel services, it also bears the burden of creation and destruction ofkernel threads. For this reason, operating systems that support this model(e.g., Windows 2000) restrict the number of threads supported by thesystem.To get around constant kernel creation, most operating systems use amany-to-many model of kernel threading, shown in Figure 4.4c. In themany-to-many model, threads are created once and remain active.

Manythreads are created on system startup, but not the number needed fora one-to-one match with user threads that make kernel requests. Thesethreads are kept around in a thread pool to service many requests. Theresult is some backlogging of requests as with the many-to-one model,but more efficient and concurrent processing of those requests as withthe one-to-one model. The many-to-many model is better adapted formultiprocessor systems, as the number of kernel threads can be tunedfor the number of processors.

Many Unix implementations support themany-to-many model.Issues with multithreadingThere are many issues that surface when we expand our concept ofprocesses and scheduling to include threads.• Thread management : threads must be managed and scheduled; theygo through states similar to processes (see Figure 4.1). Applicationscontrol the creation of threads but the actual creation and movement72PROCESSES AND THREADSthrough states is done by the kernel. Note that this adds more complexity to the idea of scheduling a process and complicates decisionsabout scheduling.

If a scheduler gives equal time to all processes, itmust choose one thread to run on behalf of a process or give a tinyamount of time to each thread in a process, so that the total time onthe threads equals the time spent on a process.• Process creation : should a thread be allowed to create a new processor just other threads within a process? If we consider an applicationthat does not create threads to be an application with a singlethread, then we cannot deny any thread the ability to create aprocess (since such an application has no real ‘main’ thread). Ifany thread can create a process, then what does the new processlook like? As we see later in this chapter, processes typically createother processes by cloning themselves.

Do we clone a process,including created threads? The answer to this is usually yes and no.Systems that support process forking (the act of cloning a process)typically give that support in two versions: with and without allthe created threads. This complicates programming with processcreation.• Thread cancellation : terminating a thread is referred to as threadcancellation. Because threads operate inside the larger context of aprocess, cancellation is not as traumatic to the system as processtermination.

In asynchronous cancellation, a thread may immediately cancel another thread. However, concurrency issues arise whenthreads are cancelled. For example, if a thread is updating data sharedby other threads in a process, what happens to the data when a threadis cancelled? Often data is corrupted when such an event occurs.This is usually remedied by using deferred cancellation. In this situation, a thread cancels itself when the system tells it to terminate butwaits for the appropriate time, for example, when no data is beingmanipulated.We referred to interrupts that operate between processes as signals.One process can signal another to indicate a particular condition. Whenan application has multiple threads, it raises the question about whichthread receives a signal when one arrives.

All threads could receive thesignal, or one or more threads could indicate they are waiting to receivea signal. Usually, all threads receive a signal sent to a process, althoughonly certain threads deal with it.AN OVERVIEW OF THE PROCESS MODEL73Active Objects in Symbian OSThreads in an operating system can be viewed as lightweight processes.As a lightweight process, a thread has many properties that a processdoes: it has an execution path, it can be scheduled, it uses resources, etc.Also, like a process, it requires bookkeeping: recording of where a threadis in its execution must occur so that the thread may be restarted when itgets a chance to execute on the CPU.

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

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

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

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