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

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

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

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

The numbers in parentheses indicate the values that are addedto the priority of the process to form the thread’s absolute priority. As thepriority of the process is changed, the relative priorities of all its threadsare automatically adjusted.Figure 9.1 shows the relative thread priorities when, for example, theprocess priority is EPriorityForeground.If you do not want your thread’s priority to be set relative to the processpriority, you can use an absolute priority instead. Absolute priorities stayfixed, regardless of the process’s priority. Figure 9.2 shows the absolutethread values that can be used, and how they relate to process priorityvalues.USING THREADS ON SYMBIAN OSRelative Thread Priorities291Process PrioritiesEPriorityLow (150)EPriorityBackground (250)EPriorityNull (−30)EPriorityMuchLess (−20)EPriorityLess (0−10)EPriorityNormal (+0)EPriorityForeground (350)EPriorityMore (+10)EPriorityMuchMore (+20)EPriorityRealTime (+30)EPriorityAbsoluteForeground (400)EPriorityHigh (450)Figure 9.1Relative Thread and Process PrioritiesYou use the same SetPriority() method to set both relative andabsolute priorities.

The function automatically determines if the priorityis relative or absolute by the argument’s enum value.9.2.4 Terminating a ThreadYou can use RThread::Kill(TInt aReason) to terminate anotherthread in the current process, either remotely or from within the thread itself.As in RProcess, RThread also provides the following methods for determining why a process has ended: ExitType() and ExitReason().ExitType() returns one of the following values:• EExitKill means that the thread function returned or that theKill() method was explicitly called.•EExitPanic means the thread ended due to a panic.•EExitPending means that the thread is still running.292PROCESSES, THREADS, AND SYNCHRONIZATIONAbsolute Thread PrioritiesProcess PrioritiesEPriorityAbsoluteVeryLow (100)EPriorityLow (150)EPriorityAbsoluteLow (200)EPriorityBackground (250)EPriorityAbsoluteBackground (300)EPriorityForeground (350)EPriorityAbsoluteForeground (400)EPriorityHigh (450)EPriorityAbsoluteHigh (500)Figure 9.2Absolute Thread and Process PrioritiesExitReason() returns one of the following values:•The return code if the thread function returns normally.•The termination reason code if the thread ends via a Kill() call.•The panic reason code if the thread exits due to a panic.•Zero if the thread is still running.9.2.5 Waiting for a Thread to EndSimilarly to RProcess, RThread has a Logon() method(RThread::Logon(TRequestStatus aStat)) that can be used towait for a thread to end.

You can wait for the signal via a call toUser::WaitForRequest() or use an active object such that theactive object’s RunL() method is called when the thread completes.9.3 Sharing Memory Between ProcessesProcesses cannot directly access each other’s memory space. For example,if you obtain a pointer to a memory buffer that resides in some otherMEMORY CHUNKS293process, and then try to directly read from or write to that buffer using thepointer, you will get a system panic. In fact, the memory pointed to bythat pointer no longer even points to the intended data since the memoryspace of a process is moved to a different area when it is not active.There are a number of ways by which processes can share data, suchas through shared memory chunks, Publish and Subscribe, the CentralRepository, message queues, and inter-process communication (IPC).

IPCusing the client–server framework will be discussed in Chapter 10, andthe new memory chunks are discussed in the next section. The otherdata transfer techniques are beyond the scope of this book, but aredocumented in the SDK documentation, and in documentation availableon the Symbian Developer Network.9.4 Memory ChunksSymbian OS provides support for shared memory regions that can beaccessed directly across multiple processes.

These shared memory regionsare known as memory chunks. You can create your own memory chunksor access existing memory chunks by using the RChunk API class.In order for your memory chunks to be shared between processes,they must be created as global (you can also have local memory chunksavailable just to a single process). Let’s look at a simple example ofcreating and using a global memory chunk://Process ARChunk chk;_LIT(KChunkName,"My Global Chunk");TInt rc=chk.CreateGlobal(KChunkName,0x1000,0x1000);if (rc != KErrNone){/* error occurred creating chunk, handle here */}TInt *ptr =( TInt *)chk.Base();//write some data into chunk using *ptrThis code creates a global memory chunk named "My GlobalChunk", and initializes it with some data.Any other program in the system can read and write this memorychunk if it knows the chunk’s name, as shown in the following://Process BRChunk chk;_LIT(KChunkName, "My Global Chunk");TInt rc=chk.OpenGlobal(KChunkName,0);if (rc != KErrNone){/* error occurred, handle here (e.g.

KErrNotFound is294PROCESSES, THREADS, AND SYNCHRONIZATIONreturned if it cannot open the chunk. */}TInt *ptr =( TInt *)chk.Base();//read from or write some data into chunk using *ptrGlobal chunks are created via the RChunk::CreateGlobal()method. The first argument is the name of the chunk. The next twoarguments specify the physical RAM assigned to the chunk (known ascommitted memory) and the amount of virtual memory to reserve for thechunk.To understand this, let’s briefly review the concepts of virtual memoryand physical memory.All addresses used by software are virtual memory addresses. Thereare 4 GB of virtual memory in the system. Virtual memory is only usableby software when it is mapped to physical memory – that is, actual RAMthat resides on the smartphone. Virtual memory is mapped to physicalmemory by the CPU’s MMU, in units of the memory page size (usually4 KB).

When virtual memory has physical memory mapped to it, it isconsidered as committed. Virtual memory addresses are very plentiful,while physical memory is a scarce resource. Refer to Chapter 3 for moredetails of memory usage in Symbian OS.Figure 9.3 shows the chunk memory layout.The committed size (the second argument of CreateGlobal())specifies the size of the memory in the chunk that you can actually readand write. You can reserve a larger block of virtual memory (via the thirdargument) when creating the chunk so that you can expand the chunk’scommitted memory, while keeping it contiguous.To expand the chunk’s committed memory size, use the RChunk::Adjust(TInt aNewSize) method, where aNewSize specifies the newsize of the committed physical memory to the chunk (starting from its baseaddress).

The committed memory can be expanded up to the reservedmaximum size specified in the third argument of CreateGlobal().For example, say you create a chunk that has 0x1000 bytes of RAMcommitted to it, with a maximum size of 0x5000:chk.CreateGlobal(KChunkName,0x1000,0x5000);At this point you only have 0x1000 bytes of physical RAM assigned toyour chunk to read and write. But you can expand the chunk later, forexample by another 0x2000 bytes:chk.Adjust(0x3000)MEMORY CHUNKS295RChunk-Home Address BaseRun Address BaseReserved SizeCommited SizeChunk Memory RegionCommited Memory (Physical RAM)Reserved Memory(Virtual Addresses)Figure 9.3 Layout of the Memory ChunkNow your chunk has 0x3000 bytes of memory assigned, and since youhad reserved 0x5000 bytes of virtual memory, the chunk memory stayscontiguous up to that maximum.RChunk::Base() is used to get a pointer to the chunk’s memoryarea.

This pointer can be used to write and read the chunk directly asneeded (note, however, that it is the programmer’s responsibility not togo out of bounds).RChunk::OpenGlobal() is used to open an already created globalchunk for access. The first argument to OpenGlobal() is the full chunkname. The second argument is used to indicate if the chunk is readonly (1) or writable (0). An Open() method also exists that uses theTFindChunk matching class to open the chunk by a partial name.TFindChunk operates similarly to TFindProcess and TFindThread(in fact you could easily convert the example in section 9.1.6 to outputall the global chunk names in the system using TFindChunk).When a process is finished with the chunk, RChunk::Close() must296PROCESSES, THREADS, AND SYNCHRONIZATIONbe called.

When the last reference to the global chunk is called, theglobal chunk itself is automatically deleted.A more secure way of using global chunks between processes is tocreate the chunk without a name and reference it by its handle. Thisis more secure since the chunk cannot be found and used by anotherprocess via TFindChunk using this method. You can pass the handle tothe chunk to another process either via client–server IPC or setting thehandle as a parameter to the other process.Here is an example of passing the handle as a parameter to a process:const TInt KChunkIndex=0;const TInt KChunkSize=0x1000;RChunk chk;chk.CreateGlobal(KNullDesC,KChunkSize,KChunkSize);...RProcess proc;LIT(KProcName,"myproc.exe");proc.Create(KProcName);proc.SetParameter(KChunkIndex,chk);proc.Resume();This code creates an anonymous global chunk, and sets the handlefor the chunk as a parameter to the myproc.exe process by callingthe RProcess::SetParameter() method.

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

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

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

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