Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 58

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 58 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 582018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

The first argument of SetParameter() is the index of the parameter (also known as the slot). Thesecond argument is the handle. After setting the parameter, the process isstarted with RProcess::Resume().Now let’s see myproc.exe retrieve that handle and get access to thechunk:// myproc.exeRChunk chunk;chunk.Open(KChunkIndex);// chunk now points to the global chunk...The version of RChunk::Open() used in this example takes a TIntas an argument, which represents the index of the parameter passed to theprocess where the RChunk handle was set.

Error checking was omittedfrom these examples for simplicity.9.4.1 Local Memory ChunksIn addition to global memory chunks, Symbian OS also provides localmemory chunks. Local chunks are similar to global chunks except thatthey can only be accessed by the process that created them. Therefore,local chunks are not useful for sharing data between processes.To create a local chunk, you use the CreateLocal(TInt aSize,TInt aMaxSize) function of RChunk, where the sizes represent theTHREAD SYNCHRONIZATION297committed memory and reserved memory of the chunk.

Note that, in thiscase, there is no name associated with the chunk, and you just access thechunk via the RChunk handle that was used to create it.You will rarely, if ever, need to use a local chunk yourself. However,Symbian OS does make use of them internally.9.5 Thread SynchronizationBeing able to execute code in parallel, using threads, is a powerful feature,but it would not be very useful if there was no way to synchronize betweenthem. After all, running in parallel is efficient – but without any coordination between the parallel strands of execution, chaos would result.Symbian OS provides several API classes for synchronization ofthreads.

In this section I will briefly cover four basic thread-synchronization functions: semaphores, mutexes, critical sections, and the RThreadand RProcess Rendezvous() method.9.5.1 Using SemaphoresYou can use a semaphore either for sending a signal from one threadto another, or for protecting a shared resource from being accessed bymultiple threads at one time.A semaphore is created and accessed with a handle class calledRSemaphore. You can create a global semaphore that can be openedand used by any process in the system, or you can create a local one thatcan only be used by the threads in your process.The following is a simple example of using a semaphore.

Assume youhave two threads: Thread A and Thread B. Assume that Thread A needsto wait for a signal from Thread B before it can process some data. Thiscan be accomplished with the following:_LIT(KMySemName, "My Semaphore");// Thread A:/* ... */RSemaphore sem;TInt rc=sem.CreateGlobal(KMySemName,0);if (rc != KErrNone){/* error occurred creating semaphore, handle it */}//have to wait for semaphore signal from ThreadBsem.Wait();/*...

signal received, ok to process data */Thread B signals Thread A when ready by://ThreadB:RSemaphore sem;298PROCESSES, THREADS, AND SYNCHRONIZATIONTInt rc = sem.OpenGlobal(KMySemName);if (rc != KErrNone){/* error occurred opening semaphore, handle it */}// do some stuff// now send a signal to thread A so it knows it can continuesem.Signal();CreateGlobal() indicates that a global semaphore is created. Sincethe semaphore was created using this function, Threads A and B inthe example need not be in the same process.

The first argument ofCreateGlobal() is the name of the semaphore (like chunks, globalsemaphores have names, local ones do not). Once the global semaphoreis created, it can be opened using the OpenGlobal() method as ThreadB does.The second argument to CreateGlobal() is a token count. Semaphores handle tokens as follows: a semaphore is created with an initialnumber of tokens. Signal() increments the semaphore’s token count byone.

Wait() decrements it by one. If Wait() finds that the decrementedtoken count has become negative (i.e., there are no more tokens), thenWait() blocks, not returning until the token count is incremented by aSignal() call.Since the initial token count in our example is 0, if the Wait() inThread A happens before the Signal() in Thread B, then Wait() willnot return until the Signal() in Thread B is called. If the Signal()in Thread B occurs first, then the Wait() in Thread A will returnimmediately since the token count was 1 before the call.The preceding example used the semaphore as a straight signal –Thread B sends a signal to Thread A.

You can also use a semaphore toprotect a shared resource, as the following example shows://ThreadARSemaphore sem;TInt rc=sem.CreateGlobal(KMySemName,1);if (rc != KErrNone){/* error occurred creating semaphore, handle it */}...sem.Wait();// access shared resource Asem.Signal(); // signal that access is finished//ThreadBRSemaphore sem;TInt rc=sem.OpenGlobal(KMySemName);if (rc != KErrNone){/* error occurred opening semaphore, handle it */}sem.Wait();THREAD SYNCHRONIZATION299// access shared resource Asem.Signal();..For this example, assume that the two threads should never accessResource A at the same time. To guard against this, the example uses asemaphore.

Thread A creates a semaphore and takes the single semaphoretoken (note the second argument of the CreateGlobal() call in ThreadA) by calling the Wait() method before accessing Resource A. If ThreadB gets to the code that accesses Resource A, it will block at the Wait()function until Thread A replaces the semaphore token with the Signal()function, at which time the Wait() call in Thread B will take the tokenand return, allowing access to Resource A.In the preceding example, only one token exists in the semaphoreso only one access to the shared resource is allowed. In some cases,however, you may want to allow multiple accesses of a resource upto a limit.

In that case you would initialize the token count to themaximum number of parallel accesses you want to permit. For example,if a semaphore was initialized with a token count of five, then areasprotected by the semaphore can be entered up to five times withoutwaiting for one to exit. A sixth one, however, will block at Wait() untilone of the other five leaves the area (indicated by calling Signal()).As with all Symbian OS R classes, when you are finished with anRSemaphore handle, you must call the Close() method for cleanup.9.5.2 Creating and Opening SemaphoresThe syntax for creating a global semaphore is:TInt RSemphore::CreateGlobal(const TDesC& aName,TInt aCount, TOwnerTypeaType=EOwnerProcess)•aName specifies the name of the global semaphore.•aCount is the initial token count for the semaphore.• aType specifies the ownership of this handle and can be EOwnerProcess (the default) or EOwnerThread.

EOwnerProcess indicates that this semaphore handle can be accessed anywhere in theprocess, whereas EOwnerThread indicates that it can be accessedonly by the creating thread.A global semaphore can be opened by name from any process or threadin the system using either:RSemaphore::OpenGlobal(const TDesC& aName,TOwnerType aType=EOwnerProcess)300PROCESSES, THREADS, AND SYNCHRONIZATIONor:RSemaphore::Open(const TFindSemaphore& aFind,TOwnerTypeaType=EOwnerProcess)The first function will open the semaphore by its full name.

The secondwill open it by a partial name, containing wildcard characters, using theTFindSemaphore class.TFindSemaphore should look familiar to you – it works like TFindProcess, TFindThread, and TFindChunk.You can also create a local semaphore by using:TInt CreateLocal(TInt aTokenCount, TOwnerType aType=EOwnerProcess)In this case, the semaphore has no name and so cannot be opened byanother process. Thus, you do not open a local semaphore – you simplyaccess it via the RSemaphore handle that was used to create it.Furthermore, if you specify aType as EOwnerThread, but wantto use the semaphore in another thread, you must use the Duplicate() method to create a copy of the handle for that thread (forfurther information, refer to the SDK documentation for RHandleBase::Duplicate()).9.5.3 The Use of Semaphores in Symbian OSSymbian OS automatically creates a semaphore, known as a requestsemaphore, for each thread on creation.

This request semaphore is thebasis of the Symbian asynchronous request functionality used by theactive object framework, described in the previous chapter, which isin turn used in the client–server framework. When an asynchronousfunction completes, the calling program’s request semaphore is used tosignal to the calling program that the function (which is running in aseparate process/thread) has generated a completion event. The functionUser::WaitForRequest() includes the execution of a Wait() onthis request semaphore.It is not, therefore, very common to have to use semaphores directly inyour programs.

But you will, almost certainly, use semaphores indirectly,through asynchronous functions and active objects. Chapter 8 discussesasynchronous functions in more detail and describes how the requestsemaphore is used by the active object framework.9.5.4 MutexesA mutex is used to protect a shared resource that can only be accessedby one thread at a time. It acts like a semaphore that has been initializedwith a token count of one.THREAD SYNCHRONIZATION301A mutex is represented by the handle class RMutex.

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

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

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

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