Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 36

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 36 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 362018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

This meansthat either the publisher, or one of the subscribers, may define a property.156INTER-THREAD COMMUNICATIONOn a secure implementation of Symbian OS, outstanding subscriptionsat the point of definition may be completed with KErrPermissionDenied if they fail the security policy check.Once defined, the property persists in the kernel until the operatingsystem reboots or the property is deleted. The property’s lifetime is nottied to that of the thread or process that defined it. This means that it isa good idea to check the return code from RProperty::Define() incase that the property was previously defined and not deleted.You can delete a property using the RProperty::Delete() function. The kernel will complete any outstanding subscriptions for thisproperty with KErrNotFound.Note that only an instance of a process from the same EXE as theprocess which defined the property is allowed to delete it, as the SIDof the process (as defined in the EXE image) is checked against the SIDof the defining process.

Also note that in a secure implementation ofSymbian OS, you may only define a property with a category equal to theSID of the process within which you are executing if the category beingdefined is greater than KUidSecurityThresholdCategoryValue.Any process may define a property with a category less than KUidSecurityThresholdCategoryValue if it has the WriteDeviceDatacapability, to ease migration of legacy code whilst still enforcing securityon defining properties.const TUid KMyPropertyCat={0x10012345};enum TMyPropertyKeys= {EMyPropertyCounter,EMyPropertyName};// define first property to be integer typeTint r=RProperty::Define(KMyPropertyCat,EMyPropertyCounter,RProperty::EInt);if (r!=KErrAlreadyExists)User::LeaveIfError(r);// define second property to be a byte array,// allocating 100 bytesr=RProperty::Define(KMyPropertyCat,EMyPropertyName,RProperty::EByteArray,100);if (r!=KErrAlreadyExists)User::LeaveIfError(r);// much later on...// delete the ‘name’ propertyTInt r=RProperty::Delete(KMyPropertyCat,EMyPropertyName);if (r!=KErrNotFound)User::LeaveIfError(r);4.4.5 Creating and closing a handle to a propertyYou carry out some property operations (such as defining and deleting properties) by specifying a category and key, but other operationsPUBLISH AND SUBSCRIBE157(such as subscribing) require a reference to the property to be established beforehand.

Some operations, such as publishing, can be done ineither way.To create a reference to a property, you use the RProperty::Attach() member function. After this has completed successfully, the RProperty object will act like a normal handle to akernel resource.When the handle is no longer required, it can be released inthe standard way by calling the inherited RHandleBase::Close()member function. You should note that releasing the handle does notcause the property to disappear – this only happens if the propertyis deleted.As I said before, it is quite legitimate to attach to a property that hasnot been defined, and in this case no error will be returned. This enablesthe lazy definition of properties.// attach to the ‘counter’ propertyRProperty counter;Tint r=counter.Attach(KMyPropertyCat,EMyPropertyName,EOwnerThread);User::LeaveIfError(r);// use the counter object...// when finished, release the handlecounter.Close();4.4.6 Publishing and retrieving property valuesYou can publish properties using the RProperty::Set() family offunctions, and read them using the RProperty::Get() family.

You caneither use a previously attached RProperty handle, or you can specifythe property category and key with the new value. The former method isguaranteed to have a bounded execution time in most circumstances andis suitable for high-priority, real-time tasks. If you specify a category andkey, then the kernel makes no real-time guarantees. See Section 4.4.8 formore on the real-time behavior of publish and subscribe.The kernel reads and writes property values atomically, so it is notpossible for threads reading the property to get a garbled value, or formore than one published value to be confused.The kernel completes all outstanding subscriptions for the propertywhen a value is published, even if it is exactly the same as the existingvalue. This means that a property can be used as a simple broadcastnotification service.If you publish a property that is not defined, the Get() and Set()functions just return an error, rather than panicking your thread.

Thishappens because you may not have made a programming error, seeSection 4.4.4.158INTER-THREAD COMMUNICATION// publish a new name valueTFileName n;RProcess().Filename(n);TInt r=RProperty::Set(KMyPropertyCat,EMyPropertyName,n);User::LeaveIfError(r);// retrieve the first 10 characters of the name valueTBuf<10> name;r=RProperty::Get(KMyPropertyCat,EMyPropertyName,name);if (r!=KErrOverflow)User::LeaveIfError(r);// retrieve and publish a new value using the attached ‘counter’// propertyTInt count;r=counter.Get(count);if (r==KErrNone)r=counter.Set(++count);User::LeaveIfError(r);If another thread is executing the same sequence to increment count,then this last example contains a race condition!4.4.7 Subscribing to propertiesA thread requests notification of property update using the RProperty::Subscribe() member function on an already attached propertyobject.

You can only make a single subscription from a single RProperty instance at any one time, and you can cancel this subscriptionrequest later with the RProperty::Cancel() member function.If you subscribe to a property, you are requesting a single notificationof when the property is next updated.

The kernel does not generate anongoing sequence of notifications for every update of the property value.Neither does the kernel tell you what the changed value is. Essentially,the notification should be interpreted as ‘‘Property X has changed’’ ratherthan ‘‘Property X has changed to Y’’. You must explicitly retrieve the newvalue if you need it. This means that multiple updates may be collapsedinto one notification, and that you, as the subscriber, may not havevisibility of all the intermediate values.This might appear to introduce a window of opportunity for a subscriberto be out of sync with the property value without receiving notificationof the update – in particular, if the property is updated again before thesubscriber thread has the chance to process the original notification.However, a simple programming pattern (outlined in the example below)ensures this does not happen.// Active object that tracks changes to the ‘name’ propertyclass CPropertyWatch : public CActive{enum {EPriority=0};public:PUBLISH AND SUBSCRIBEstatic CPropertyWatch* NewL();private:CPropertyWatch();void ConstructL();∼CPropertyWatch();void RunL();void DoCancel();private:RProperty iProperty;};CPropertyWatch* CPropertyWatch::NewL(){CPropertyWatch* me=new(ELeave) CPropertyWatch;CleanupStack::PushL(me);me->ConstructL();CleanupStack::Pop(me);return me;}CPropertyWatch::CPropertyWatch() :CActive(EPriority){}void CPropertyWatch::ConstructL(){User::LeaveIfError(iProperty.Attach(KMyPropertyCat,KMyPropertyName));CActiveScheduler::Add(this);// initial subscription and process current property valueRunL();}CPropertyWatch::∼CPropertyWatch(){Cancel();iProperty.Close();}void CPropertyWatch::DoCancel(){iProperty.Cancel();}void CPropertyWatch::RunL(){// resubscribe before processing new value to prevent// missing updatesiProperty.Subscribe(iStatus);SetActive();// property updated, get new valueTFileName n;if (iProperty.Get(n)==KErrNotFound){// property deleted, do necessary actions here...NameDeleted();}else{// use new value ...159160INTER-THREAD COMMUNICATIONNameChanged(n);}}4.4.8Real-time issuesWhen designing this functionality, we wanted to ensure that publishinga new value to a property was a real-time service, since time-criticalthreads will surely need to invoke it.

For example a communicationprotocol could use publish and subscribe to indicate that a connectionhas been established.However, there can be an arbitrarily large number of subscriptions onany given property, which makes publishing to that property unbounded.We solved this problem by using a DFC queued on the supervisor threadto do the actual completion of subscriptions. The publisher updates thevalue of the property and the kernel then places the property on a queueof properties for which notifications are outstanding.

The DFC, in thesupervisor context, then drains the queue and notifies subscribers.As I showed earlier, you should publish or retrieve properties by usinga previously attached RProperty handle, rather than by specifying theproperty category and key with the new value. This is guaranteed to have abounded execution time, unless you are publishing a byte-array propertythat has grown in size.

In this case the kernel will have to allocate memoryfor the byte-array, and memory allocation is an unbounded operation.4.5 Shared chunks and shared I/O buffersShared I/O buffers and shared chunks are mechanisms which allowyou to share memory between a user-side process and a kernel-sideprocess, with a minimum of overhead. Such sharing avoids the expensiveand time-consuming act of copying (potentially) large amounts of dataaround the system. Note that shared I/O buffers are a legacy mechanismprimarily aimed at providing compatibility with EKA1 and that sharedchunks, which are much more efficient and flexible, are the preferredmechanism for sharing memory between device drivers and user threadsin EKA2.

To understand how these mechanisms work, you need to knowa little more about how Symbian OS manages its memory, so I will coverthem in Chapter 7, Memory Models.4.6 SummaryIn this chapter, I have covered several of the mechanisms that EKA2provides to allow communication between threads: client-server, messagequeues, publish and subscribe, shared I/O buffers and client-server.

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

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

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

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