Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 26
Текст из файла (страница 26)
See epoc32\include\connect\sbdefs.h for moreinformation on the shared types used.Variants and Extensions• Many Publishers, Single SubscriberNormally an event generator defines a property in order to be ableto share a property value with one or more event consumers. Such isthe convenience of this pattern that occasionally an event consumermight define a property in order to subscribe to the property itself,defining a suitably permissive write policy for the property such that128EVENT-DRIVEN PROGRAMMINGone or more other event generators are able to update the propertyvalue.While this is of limited use if the property owner–subscriber mustknow each value of the property, it can provide a convenient meansof allowing external components to trigger some action in the eventconsumer while remaining very loosely coupled.
This enables easycustomization of the event consumer since it is not reliant on eventgenerators even being present and reacts immediately once they areinstalled on the device.• Multiple Publishing FrequenciesWhen a property is changed, all event consumers are notified. Thisleads to their threads running to service the event signal. If a propertychanges value frequently, it is wasteful for event consumers to performsubstantial processing for each event signal.Take a property representing signal strength as an example.
Potentially, this could be updated several times a second. If a change invalue were used only to update the UI signal bar, it would not beharmful. However, if it were used by many entities for serious processing (e.g. checking email, sending unsent SMS messages, re-connectingto the Internet), then such frequent updates would have a severe effecton battery life.Nevertheless, it is obviously desirable for many components of adevice to know about the state of network coverage and to take appropriate action.
In cases like this, it may be worth the event generatordefining multiple properties with associated update characteristics.For example, raw signal strength (updated more than once a second),periodic signal strength (updated once every 10 seconds) and networkcoverage (updated only when moving between some network signaland none). Each event consumer can then monitor the appropriatenotification and so reduce the number of threads that run when theunderlying value changes.References• Publisher–Subscriber [Buschmann et al., 1996] describes a similarpattern for a different context.• Event Mixin (see page 93) is often composed with this pattern toseparate the responsibility of subscribing to an event from handlingthe event signal.• Active Objects (see page 133) is often composed with this pattern toavoid the need to synchronously wait for the event signal to complete.PUBLISH AND SUBSCRIBE129• Client–Server (see page 182) and Coordinator (see page 211) canbe combined to provide a solution to reliable event signals that thispattern doesn’t support.• Escalate Errors (see page 32) is used to handle errors when dealingwith the RProperty API.• Request Completion (see page 104) provides more details on howTRequestStatus is used as an event signal within the Publish andSubscribe pattern.• The following document provides additional information on the publish and subscribe technology: Symbian Developer Library SymbianOS guide Base Using User Library (E32) Publish and Subscribe.5Cooperative MultitaskingMultitasking is where multiple tasks share common resources such as aCPU or data.
In the case of a device with a single CPU,1 only one task issaid to be running at any point in time, meaning that the CPU is activelyexecuting instructions for that task. Multitasking involves schedulingwhich task is to be the one running at any given time whilst all other taskswait to be given a turn. By switching between tasks frequently enough,the illusion of parallelism is achieved.
One thing to remember here is thatmultitasking is a more general concept than multithreading since whilstindividual tasks can be assigned to run in a single thread this is not alwaysnecessary.As discussed in Chapter 4, Symbian OS makes extensive use of eventdriven programming to conserve power whilst promoting the decouplingof components. This naturally leads to multitasking as any moderatelycomplex software will need to deal with incoming event signals frommultiple sources. Early GUI systems took a step backwards from thebig systems of the previous era by implementing their event-drivenprogramming models using non-pre-emptive process scheduling (cooperative multitasking as it became known).
This was in contrast to theUNIX and mainframe approach of pre-emptive process scheduling, inwhich the currently running process can be swapped out at any timeby the operating system scheduler. In a non-pre-emptive system, thescheduler chooses the process which will run next, but always lets itrun to completion. Pre-emption incurs more overhead and makes thesystem more complex. But the non-pre-emptive approach has the seriousdrawback that badly behaved applications can break a co-operativesystem by not yielding to allow other processes to be scheduled.Multithreaded systems introduce finer-grained, lighter-weight threadmanagement, in addition to process management, as an attempt to keep1At the time of writing, all Symbian OS applications run on a single CPU but this is setto change in future with SMP (www.symbian.com/symbianos/smp).
However, multitaskingwill still occur on each individual CPU.132COOPERATIVE MULTITASKINGthe benefits that multiple process systems bring, including asynchronousand event-driven programming paradigms and fully pre-emptive systems,without suffering their performance penalties. The price we pay for this isincreased software complexity. Two problems in particular make writingmultithreaded programs difficult and error prone:• Synchronization – for example, to control the execution order of yourthreads.
This is necessary if the sequence in which your threadscomplete would otherwise be indeterminate.• Shared data and the problem of atomicity – reads and writes from onethread may be invalidated partway through by a pre-empting threadrewriting the data. This requires that these data reads and writes areatomic such that once a thread has begun an operation no other threadcan attempt the same operation until the first thread has finished.So while multithreading is becoming increasingly common in applications programming,2 most systems leave the individual developer tosolve these problem of complexity. Many systems, including Symbian OS,provide tools (mutexes, semaphores, critical sections, etc.) that help allowyou to co-ordinate threads and handle user events but these only make itpossible to write multithreaded code rather than solve the problem.Another aspect to consider is the overhead of each thread on a SymbianOS device with limited RAM.
As discussed in Appendix A, a thread usesby default at least 17 KB of RAM.The ideal situation for Symbian OS is to have pre-emptive schedulingof multiple different processes across the system combined with singlethreading of each process to give us cooperative multitasking withina process.The patterns in this chapter provide a way of doing just that.
ActiveObjects (see page 133) describes the basis of the Symbian OS approachto cooperative multitasking within a single thread whilst AsynchronousController (see page 148) builds on that by describing a technique toorganize a series of related sub-tasks to achieve some larger task.2 Itused to be the preserve of systems and server programmers.ACTIVE OBJECTS133Active ObjectsIntentEnable efficient multitasking within a single thread by using the SymbianOS active object framework.AKANone knownProblemContextYour application or service needs to continue executing other tasks whilewaiting for the completion of an asynchronous service.Summary• You wish to reduce your maintenance costs, such as by reducing thetime that you spend debugging your software.• You wish to reduce the time that you need to spend testing yoursoftware looking for defects.• You wish to reduce the amount of RAM used by your software,for example by reducing the number of threads running in yourprocess.DescriptionThere are many kinds of services that are naturally asynchronous andwhich therefore expose asynchronous APIs to clients.
In general, asynchronous APIs are likely to be found wherever you have an interfaceto a component that is unpredictable or irregular; has a potentially highresponse time;3 or which in any sense displays indeterministic behavior. A good strategy is to treat virtually any event signal coming fromoutside the current process in an asynchronous manner so that youare less dependent on components outside of your control. Examplesof this range from end users generating input of any kind to communication lines that can go down and phones that could get left off thehook.Any program that deals with event generators, invokes callbacksor shares a resource through Client–Server (see page 182) will haveto deal with asynchronous APIs.
All event-driven programs, includinginteractive applications, are naturally asynchronous, at least in theirevent handling.3 Knownas latency.134COOPERATIVE MULTITASKINGServices provide asynchronous APIs to allow them to be decoupled from their clients. The way that this works is that requests aremade to the service and are guaranteed to return immediately.