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

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

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

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

In Figure 4.6, at the dotted line labeled ‘A’, there are fourprocesses executing. Join operations cause the subprocesses to terminateand combine their executions. By the end of Figure 4.6, there is a singleprocess executing again.In Linux, for example, a process creates a new process by calling thefork() system call. This system call creates a new process by cloningthe current process’s PCB. The result is two processes that look identical;80PROCESSES AND THREADSforkforkforkAAjoinjoinjoinFigure 4.6The interaction between fork and join operationsthe new one is an exact copy of the old one.

Both processes continueexecution at the point of the fork() system call. The child knows it is achild because the fork() call returns a zero; the parent knows it is theparent because the fork() call returns a non-zero result, which is theprocess ID of the child process.As an example, consider the following simple code:#include <stdio.h>void main(){PROGRAMMING WITH PROCESSES81int pid, status;pid = fork();if (pid == 0){printf("This is the child!\n");sleep(60);}else{printf("This is the parent! Child’s PID = %d\n", pid);wait(&status);printf("Child terminated...status = %d\n", status);}}The first executable code line is:pid = fork();Before this line, there is a single process.

After this line executes, thereare two processes. For one process, the child, pid has the value 0. Forthe other process, the parent, pid has a non-zero value that is the processID of its child. In the example, the child simply prints a message, sleepsfor 60 seconds, and terminates. The parent executes the line:wait(&status);which implements a join operation in Linux. A wait() call moves thecaller process to the ready queue until the process for which it is waitingterminates. In this case, the call is waiting for the termination of anyprocess the parent created.Processes terminate in many ways. The normal way for a program toend is to simply run out of code. Most programming languages providefor some kind of call to exit(). In addition to allowing programs andprocesses to use the exit() system call, processes can also terminatetheir children.

Signals that tell a process to terminate can be sent arbitrarilybetween processes, but ones sent from a parent to a child process areespecially hard to ignore.In this conventional process model, processes share very few resources.Each newly created process works in its own environment with its ownPCB. This means each process has its own variables, its own access to82PROCESSES AND THREADSresources and its own access to the kernel. What is shared are systemresources such as input/output devices and memory.

As we have discussedbefore, operating systems are designed to protect resource access and toshare system resources in a very orchestrated manner, so that multipleaccesses do not corrupt resources. This means that even though a child iscreated by a parent, they are peers from the point of view of the resource.This conventional approach to multiprogramming is very resourceintensive. The operating system must keep track of each process byrecording and manipulating its PCB. Switching context between processesis expensive, because PCB data must be recorded and moved into and outof memory.

Creating processes is also expensive because of PCB creationand the cloning of the parent context.Sharing data between processes is quite difficult. The operating systemputs up a barrier between processes and protects each process fromothers. Data can be shared in Linux by creating global, shared memorythrough system calls or by creating data channels called pipes that aprocess can share with children that it creates.

However, these methodsare special cases and are themselves expensive to the operating system.Consider a sorting algorithm. In a quicksort implementation, an arrayof data elements is split up into pieces and a recursive call is made tothe quicksort algorithm to work on each piece.

The quicksort algorithmcan be implemented in a parallel manner, where each recursive call isreplaced by a new process. If we use the conventional model, we can getmany processes involved. These processes can easily get started on thesorting process, because each has a copy of the data array (as the PCBis cloned). However, when it comes time to put the sorted pieces backtogether, the conventional model makes implementation very difficult.Somehow, only pieces of the data array must be communicated to a singleprocess, which must put everything back together. Parallel versions ofquicksort are rarely implemented with processes.Programming with ThreadsThreads solve many of the difficulties with processes.

Threads are easilycreated: the creation process is lightweight because it is not resourceintensive, no PCBs are cloned. Ideas of forking execution and joiningthreads together still exist for threads, because they are truly parallelentities. However, working with threads is much easier.Again consider Linux, so that we can compare it to the examplesabove. The following code contains a simple program to create and jointhreads of execution in a program.PROGRAMMING WITH PROCESSES83#include <synch.h>#include <thread.h>#include <unistd.h>void *child (void* args){printf("This is the child!\n");sleep(60);}void main(){thread_t yarn;thr_setconcurrency(2);thr_create(NULL, NULL, child, NULL, 0, &yarn);printf("This is the parent!\n");thr_join(yarn, &yarn, NULL);}Notice that each thread of execution is implemented by its ownfunction and concurrent threads are defined by function definitions. Thecode produces a child that prints a message and terminates, becauseits definition terminates.

The parent creates the thread through a call tothr_create(). The parent waits to join its execution thread with thechild’s by calling thr_join(). This call blocks until the child specifiedby the yarn descriptor terminates.Threads help to mitigate the difficulties found in the conventionalprocess model. Thread creation is easy and lightweight; thread contextswitching happens within a PCB. The operating system still has to keeptrack of threads, but bookkeeping requires less data. In addition, threadsallow sharing of all resources of the parent.The quicksort algorithm lends itself easily to a thread-based implementation, because recursive function calls can be replaced by threadcreation. Like functions, threads share memory and the quicksort algorithm marks off portions of the same data array for each function or threadto work on.

Joining the pieces back together is irrelevant, because eachthread worked on a portion of the same array.Programming in Symbian OSSymbian OS supports processes, threads and active objects, the specialcase of threads focused on external events. Symbian OS supports standard84PROCESSES AND THREADSand conventional interfaces, which allow processes and threads to beused in much the same way as on other systems such as Linux.

SymbianOS supports the concepts of forking and joining processes, but does notclone a PCB when forking (it implements a ‘fresh’ executable image, notduplicated from the parent). There are a few other differences, but theydo not affect the global concepts of process creation. Symbian OS alsosupports the POSIX thread manipulation APIs.Active objects are unique to Symbian OS.

Recall that active objectsare Symbian OS threads that multitask cooperatively, that is, they aredesigned to facilitate asynchronous requests that wait for external events,usually tied to device I/O. The keys to using an active object are thateach active object must release control to the operating system when it isready to wait for an external event and that each active object must keeptrack of its internal state, because execution is restarted at the same placeevery time it restarts.In Symbian OS programming, active objects are derived from theCActive class, which provides access to a CActiveScheduler object.An active object must implement at least two functions:void RunL()void DoCancel()The RunL() function is the heart of an active-object implementation.Upon construction, the active object creates and initializes anything itneeds.

To inform the operating system that an asynchronous request hasbeen submitted (that the active object must wait for), the active objectcalls the function SetActive(). This suspends the active object thread,turning control of the asynchronous operation over to a scheduler. Whenthis operation completes and generates an event the active object hasregistered for, the scheduler calls the RunL() function for the activeobject.The DoCancel() function must be implemented to cancel the actionsimplemented by the active object. On receiving a request to cancel theoperations for an active object, the system first checks whether there isan outstanding request for this object, then calls DoCancel().There must be a way to start the active object. This should be a functionthat initializes the active object and executes the first asynchronousrequest.

This function then passes control to the scheduler by callingSetActive().PROGRAMMING WITH PROCESSES85Consider an example that sends an object over the serial port of aSymbian OS device. We could start this sending process by calling thefollowing function:void TodoXferSerialAO::SendItem(CAgnEntry *aEntry){iEntry = aEntry;CParaFormatLayer *iParaFormatLayer = CParaFormatLayer::NewL();CCharFormatLayer *iCharFormatLayer = CCharFormatLayer::NewL();// Set up to-do item dataiTodoItem = CAgnTodo::NewL(iParaFormatLayer, iCharFormatLayer);iTodoItem = (CAgnTodo *)(aEntry->CastToTodo());priority = iTodoItem->Priority();duedate = iTodoItem->DueDate();// Start the protocoliAppUi->SetProgress(_L("Starting the protocol"));buffer.Copy(KReady);Send(buffer);iSendingState = ESendingState1;}The SendItem() function receives a to-do list entry (the parameterfrom the CAgnEntry class), prepares it for sending, then calls a Send()function to send the object through the serial port.The Send() function is defined as follows:void TodoXferSerialAO::Send(const TDes8& aText){TInt len;TBuf8<100> buffer;len = aText.Length();// Send the lengthbuffer.SetLength(0);buffer.Append((TChar)(48+len));buffer.Append(aText);commPort.Write(status, buffer, len+1);SetActive();}There are some interesting parts of this implementation.

First, note thestructure of the code: it sets up some parameters for serial communication86PROCESSES AND THREADSand then calls Write(). This is an asynchronous call that returnsimmediately, beginning the communication process in parallel. Secondly,we use a variable – status – to remember the state we are in. Finally,notice the use of SetActive() at the end of the code. When this systemcall is performed, the active object’s execution is terminated and thethread is placed on a waiting queue.Once we have started an active object and turned over control tothe scheduler, we need a way to continue its execution wheneverI/O operations complete. This is found in the implementation of theRunL() function. The most common pattern embraced by this functionis essentially to use one big switch statement, based on the value of thestate variable.

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

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

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

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