Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 48
Текст из файла (страница 48)
Such properties are communicated to more than one interestedpeer asynchronously.The publish and subscribe API can be used by both user- and kernelside programs, via similar APIs, and thus can also provide asynchronouscommunication between user- and kernel-side components.
Only userside usage is discussed in this text.As shown in Figure 8.2, publish and subscribe threads may have therole of either the publisher or the subscriber, while any thread can be theone which defines the property to be published. Such properties are single data values, uniquely identified with an integral key. Properties haveidentity and type. The identity and type of a property is the only information that must be shared between a publisher and a subscriber – thereis no need to provide interface classes or functions, though that may bedesirable in many designs.There are six basic operations that can be performed on properties:• define: create a property variable and define its type and identity• delete: remove a property from the system• publish: change the value of a property• retrieve: get the current value of a property• subscribe: register for notification of changes to a property• unsubscribe: deregister for notifications of changes.Of these operations, the first two need to be coupled in the same thread,as it is only permissible for the defining thread to delete a property.
Once244INTERPROCESS COMMUNICATION MECHANISMSIPC boundaryIPC boundarysetPublishersetPublisher/SubscriberPropertiesSubscribergetgetPublishersetgetSubscriberKernel spaceFigure 8.2 Publish and subscribe IPC mechanismdefined, the property persists in the kernel until Symbian OS reboots orthe property is deleted. Its lifetime is not tied to that of the thread orprocess that defined it. When properties are deleted, any outstandingsubscriptions for the property are notified of the change, indicating thatthe properties can no longer be found. An idiosyncrasy worth noting isthat the thread defining (and deleting) a property does not necessarilyhave rights to publish it or subscribe to it.Since both publishers and subscribers are allowed to define a property,it is not essential for a property to be defined before it is accessed.
Thisparadigm allows for lazy definition of properties and publishing a propertythat is not defined is not necessarily a programming error.For some operations, such as publication and retrieval of properties,there are two modes of transaction. Although P&S operations are connectionless, they can be used either transiently or after having set up theassociation between user and property in the kernel. Thus publishers andsubscribers may ‘attach’ to properties prior to operation.Subsequently, properties can be published or retrieved, either by usinga previously attached handle or by specifying the property categoryand key associated with the new value. In EKA2, a previously attachedhandle has the benefit of deterministic, bounded execution time, suitableOVERVIEW245for high-priority, real-time tasks.
However, an exception to this benefitoccurs when publishing a byte-array property that requires allocating alarger space for the new data.Properties are read and written atomically, so it is not possible forthreads reading the property to get an inconsistent value, or for multiplesimultaneously published values to be confused.As far as subscriptions and cancellations are concerned, clients of P&Smust register their interest, by attachment, prior to usage. This is due tothe asynchronous nature of the notification. For the kernel to recognizedeterministically which threads need to be notified of a change in someproperty, that interest must be associated with the property.Notification of a property update happens in four stages: a clientregisters its interest in a property; the property’s value is published; theclient is notified of the publication (by completion of its subscriptionrequest); after notification, the client initiates retrieval of the updatedproperty.Message Queues IPCContrary to the connection-oriented nature of client–server IPC, messagequeues offer a peer-to-peer, many-to-many communication paradigm.Using the Message Queue API, threads may send messages to interestedparties without needing to know if any thread is listening.
Moreover, theidentity of the recipient is not needed for such communication.There are five basic operations that can be performed on a messagequeue:• creating or opening a message queue• sending a message• receiving a message• waiting for space to become available in the queue• waiting for data to arrive in the queue.Message queues can be named and visible to all processes, anonymous but visible to all processes, or local to the current process only.The message queues themselves are managed by the kernel and aresized at the time of their creation, which allows for real-time, deterministic delivery of messages in EKA2, for both sending and receiving ofmessages.Threads that use message queues must obtain a valid handle in orderto access a particular queue.
They may then send (i.e., add) messagesto, and receive (i.e., remove) messages from, the queue. Subsequently,a queue may run out of space, in which case senders can either block246INTERPROCESS COMMUNICATION MECHANISMSon sending or be notified that a queue overflow would occur and thusbe allowed to retry later. Similarly, on message reception, readers caneither block indefinitely until a message arrives in the queue or benotified asynchronously if there is no message pending for reception andretry later.
Software developers therefore have the choice as to whichmessage-sending semantics to employ.Although it is possible for queues to have multiple readers, in mostcases such an arrangement needs to be combined with some sort ofout-of-band collaboration between the reader threads.Message queues effectively allow for fire-and-forget communicationsemantics between threads. Readers are guaranteed the delivery of messages to the queues, but delivery to final recipients is not guaranteed.Moreover, neither messages nor queues are persistent; they are referencecounted objects that are cleaned up when the last handle to the queueis closed. Both send and receive operations effectively copy the messagestructures to and from the kernel.A thread may query a queue to find out if it has space available formessages or if any messages are pending for delivery.
Moreover, a threadcan interrogate the queue as to its message size. Additionally, a threadmay choose to wait for a queue until data or space becomes available.With the Symbian OS Message Queue API, queues can also be typedso that it is possible to send and receive only messages of a specific type.This paradigm allows for type-safe IPC between participants without theoverhead of type checking and the potential errors that may arise.In general, since the size of the messages that can be exchanged inthis API is relatively small (between four and 256 bytes), queues lendthemselves nicely to timely event notification from many sources toSenderthreadReceiverThreadQueueSenderthreadSenderthreadFigure 8.3 Message queue IPC mechanismCLIENT–SERVER IPC247one recipient, as well as being an efficient means of passing memorydescriptors and pointers between threads in the same process.
This latterusage is usually implemented via local queues and can be employedeffectively for processor-intensive and multimedia applications.8.2 Client–server IPCClient–server communication begins with the client building a session tothe corresponding server, which is then used by the client and the serverto pass messages and data. There are eight main high-level abstractionsthat a developer implementing client or server code must be aware of:RServer2, CServer2, CSession2, RMessage2, RMessagePtr2,RSessionBase, RSubSessionBase and TIpcArgs.To associate a client API with a server (see Figure 8.4), you need touse an RSessionBase to connect to an object derived from CServer2.This creates an object derived from CSession2 in order to handle theserver’s side of the session. When the session is established, messagesand data can be communicated to the server and data is written back tothe client using an RMessage2 object.Client-side Server-side1communicationCServer2ownership4RSessionBase2assocciationRServer2creation order1..6CSession26User-sideKernel-sideDServerDSession35Figure 8.4Details of client–server IPC mechanismSetting up a SessionIn order for a client thread to use a server, it needs to establish a sessionwith that server.
To do so, the client calls the CreateSession() method248INTERPROCESS COMMUNICATION MECHANISMSof the RSessionBase class, passing the name of the server to which itwants to connect.In order to associate a client with a server, the Symbian OS kernelinternally creates a new DSession kernel object that is then attached toa DServer kernel object which represents the server.class CSession2 : public CBase{friend class CServer2;public:IMPORT_C virtual ∼CSession2() = 0;private:IMPORT_C virtual void CreateL(); // Default method, does nothingpublic:inline const CServer2* Server() const;IMPORT_C void ResourceCountMarkStart();IMPORT_C void ResourceCountMarkEnd(const RMessage2& aMessage);IMPORT_C virtual TInt CountResources();virtual void ServiceL(const RMessage2& aMessage) = 0;IMPORT_C virtual void ServiceError(const RMessage2& aMessage,TInt aError);protected:IMPORT_C CSession2();IMPORT_C virtual void Disconnect(const RMessage2& aMessage);IMPORT_C virtual TInt Extension_(TUint aExtensionId, TAny*& a0,TAny* a1);...private:TInt iResourceCountMark;TDblQueLink iLink;const CServer2* iServer;TAny* iSpare;};For the attachment to go through and the session to be set up, the serverreceives a connection message.
Consequently, session establishmentin EKA2 is, in effect, a two-stage process, allowing for asynchronousoperation (should the client choose to do so).On session connection, the CServer2-derived server object callsNewSessionL() to create a new CSession2-derived object that represents the server-end of the session and to which future messages arerouted.CServer2 is an active object whose RunL() method delivers RMessage2 message references to the corresponding CSession2::Serv iceL() methods.Server Start-upAs mentioned earlier, a server needs a mechanism to receive connectionsand messages before a client can establish a session with it. Since theonly route to communicate with a server is via the kernel, the mechanismCLIENT–SERVER IPC249is provided by an RServer2 proxy and its corresponding DServerobject (which represents the server resource in the kernel).