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

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

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

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

The abstractness of the model can be seen in how it is used: eachside simply writes data to and reads data from a socket as if it was anyother local I/O device. Each side really does not know (or care) how theother side reads or processes the data. In fact, the socket may implementINTERPROCESS COMMUNICATION131translation of data, again without each side knowing (or caring). Thetranslation is implemented by the operating system and occurs as the datais transferred between the endpoints.

These translations may be as simpleas little-endian to big-endian or as complicated as using the Bluetoothprotocol.Sockets have certain properties, chosen based on how they are used.A socket is either connected or connectionless. A connected socketmaintains a virtual connection between the two endpoints. This meansthat address information for the remote endpoint needs to be given onlyonce, and that each access to the connection can be done withoutspecifying this information again.

A connectionless socket forces theapplication to specify the remote endpoint information each time it isused and has no virtual connection. A connected socket is easier to useand is more reliable yet requires higher overhead in its implementation.Connected sockets use mechanisms to ensure that data arrives at theremote endpoint in the exact order they were sent and that they arriveerror-free or do not arrive at all. Connectionless sockets make no suchguarantees about data arrival or reliability.Connected sockets are implemented with streams.

A stream is alogical connection between two endpoints that implements the followingproperties:• reliability : with a stream, data is delivered accurately (as they weresent) without error or it is not delivered at all; if there is no datadelivery, this is detected and the socket owner is notified• error control : errors are detected automatically and the remote endpoint is usually asked to retransmit the data packet that had the error;maintaining error control usually involves using checksums on datapackets and forcing remote endpoints to acknowledge when theyreceive packets• ordered delivery : data that flows between two endpoints can bebroken up and sent as fragments; a stream makes sure those fragmentsarrive at their destination in the order in which they were sent andthat the larger data packets are reassembled correctly.The reliability of connected sockets comes at a price. There are moreprotocol layers involved and hence more protocol overhead.

There ismore communication between endpoints and hence more data traffic.132PROCESS CONCURRENCY AND SYNCHRONIZATIONRemote Procedure CallsRemote procedure calls (RPCs) describe a very commonly used set ofIPC semantics. Using the phone model of IPC, if we force the senderto identify the receiver, and block the sender until the receiver is doneprocessing the message that was sent, we then have semantics that mirrorthose of procedures in a programming language. The act of sending ismuch like the act of calling a procedure, except that the procedure is ona remote process.To complete the analogy, we need a few more concepts. When aprocedure call is made, data is transferred to the called procedure inthe form of parameters and passed back to the caller in the form of areturn value.

We can use these ideas for RPC: the RPC call transfers datafrom sender to receiver and the receiver can send data back througha return value abstraction. These facilities need the same ‘translation’abstraction as sockets: the movement of data between sender and receiverassumes that the receiver can read what the sender has written. Issues ofendianness of the architecture or error control are to be worked into theimplementation of RPC. All the sender has to worry about is calling andreturning.RPC mechanisms are common in networked environments.

Theabstraction is similar to the socket abstraction, except that data doesnot flow back and forth arbitrarily. Data is sent in a single messageand received when the remote procedure is done. RPC mechanisms areuseful in situations where short messages must be exchanged but controlis required. RPC is analogous to the stream mechanism.IPC in Symbian OSIPC is central to the implementation of Symbian OS.

Since it has a microkernel design, much of the operating system’s functionality is pushedinto servers running at the user level. These servers communicate witheach other, with the kernel and with user applications on a socket-based,client–server-oriented basis.User-level objects in Symbian OS use a socket-based system to communicate. A user-level server is an active object (remember active objectsfrom Chapter 4?) that waits for connections with requests and servicesthem. Data is exchanged through the sockets via objects from the RMessage2 class. Remote procedure calls are not used in Symbian OS.MANAGING DEADLOCKS1336.8 Managing DeadlocksWhen processes wait for each other, either directly or in some circularmanner, we call the situation a deadlock. Consider a simple situationof a bank transfer.

Let’s say that two processes – say, two people at twoautomated teller machines – desire to transfer funds between the sametwo accounts. The processes that they go through are shown in Figure 6.2.In the simple scenario where Process A executes its first statement,followed by Process B executing its first statement, deadlock ensues whenProcess A executes its second statement and Process B executes its secondstatement. This is because Process A is waiting for Process B, which iswaiting for Process A.For a deadlock situation to occur, four conditions must be present:• at least one resource must be acquired for exclusive use by a process• that process must be waiting to acquire another resource in the system• a circular waiting set must exist, where each process is dependent onresources held by another process• pre-emption cannot be allowed to free resources.Deadlock situations require that the operating system detects andrecovers from deadlocks. Deadlock detection is a matter of analyzingthe relationships between processes.

The operating system should maintain a table of structure resource requests. When a process requestsaccess to a resource that is allocated to another process, an entry in thestructure should indicate the waiting relationship. The result is a graphProcess AProcess Block (account A)lock (account B)lock (account B)lock (account A)decrement $100 from account Adecrement $100 from account Bincrement account B by $100increment account A by $100unlock (account B)unlock (account A)unlock (account A)unlock (account B)Figure 6.2 Process definition for transferring money134PROCESS CONCURRENCY AND SYNCHRONIZATIONof relationships between processes.

This graph needs to be checkedperiodically for cycles. When a cycle exists, a deadlock situation hasoccurred.Recovering from a deadlock situation can be a difficult operation. Thereare two ways to break a deadlock: process termination and resource preemption. To break a deadlock by process termination, the operatingsystem needs to terminate one or more processes that are involved in thecycle detected in the resource allocation graph. Terminating all processesis a simple solution; finding and terminating only one crucial process canbe difficult. The single-process approach is a decision based on manyfactors, including the priority of the process, the length of time the processhas been executing, how many other resources are used by the process,and how many resources are still needed by the process.To break a deadlock by resource pre-emption, the operating systemmust choose the resource and the process to pre-empt.

Sometimes thischoice is simple: a single resource may be the logjam and it maybe obvious which process has that resource. However, there must becomputable ways to make this choice. In addition, once the deadlock isbroken, it may occur again and we must somehow ensure that the sameprocess accessing the critical resource is not always chosen again (thatwould cause a starvation situation). Another, more gentle, approach is torollback a process to a safe state. The process under examination is notterminated but reset to a state where the critical resource can be allocatedto another process. Most of the time this actually means restarting theprocess, because determining a safe state usually is not possible.6.9 SummaryThis chapter has been devoted to issues surrounding the concurrency ofprocesses in an operating system.

We first introduced what happens whenprocess interleave their statements and instructions. We then describedthe goal of serializability and ways that we could algorithmically synchronize processes to share resources properly. We introduced semaphores asa way to make synchronization easier. We developed other abstractionsthat built on and expanded semaphores. We then worked through theDining Philosophers’ Problem and demonstrated semaphores in Linux.We then discussed concurrency in Symbian OS.

We introduced interprocess communication via message passing, sockets, and remote procedurecalls. We finished the chapter by discussing ways to manage deadlocks.EXERCISES135Exercises1.We discussed busy waiting as a special case of waiting in anoperating system. What other kinds of waiting can go on in anoperating system?2.How is it possible to execute only half of a statement before acontext switch is made?3.We stated that making processes be truly serial – executing oneafter the other – would have a bad effect on performance.

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

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

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

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