|
Volume Number: | 10 | ||
Issue Number: | 12 | ||
Column Tag: | Enhancing Sprocket |
Related Info: Apple Event Mgr SCSI Manager
Adding Threads To Sprocket
Programming like you had a “real” OS
By Steve Sisak, Articulate Systems
Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.
About the Author
Steve Sisak - Steve lives in Cambridge, MA, with three Macintoshes, two Newtons, and two neurotic cats. He referees Lacrosse games, plays hockey, drinks beer, and searches for the perfect vindaloo. He also finds time to work on a speech recognition system for Articulate Systems during the day, a multithreaded communication server and thread-savvy studio library at night, and a variety of odd jobs the rest of the time.
Introduction
Last month, in Randy Thelan’s article “Threading Your Apps”, you learned a bit about the theory behind the Threads Manager and how to call its routines. This month, we’ll skip past the theory and focus on how you can combine the Threads Manager and the AppleEvent Manager, with the help of a couple of small libraries, to make the job of writing a modern Macintosh application much easier. Rather than cover every aspect of the Threads Manager, we will concentrate on a few key features that can really save you time. In fact, if you’re using the libraries as-is, you may never need to call the Threads Manager directly at all. The libraries, AEThreads and Futures, are useful as both stand-alone libraries and as non-trivial examples of multi-threaded code. In addition, in what I hope continues as a good trend, I have integrated them into the MacTech application framework, Sprocket. We’ll start with a quick overview of the libraries, continue with a description of how to use them, and finally delve into the details of how they’re implemented. Even if you only plan to use the libraries as-is, this section should help you to understand threaded programming and may also help you avoid traps and pitfalls I’ve already encountered.
The application model we’ll be using is a threaded extension of the fully factored application that Apple has been begging us to implement for the last few years - it is split into a user interface portion and a server portion which communicate with each other using AppleEvents. The difference is that, instead of handling each event sequentially, the AEThreads library allows the server portion of the application to handle multiple events concurrently and asynchronously, each in a separate thread of execution. It takes care of all of the bookkeeping involved with spawning and cleaning up after the threads, suspending and resuming the AppleEvents, and reporting errors to the AppleEvent Manager. Further, the Futures library provides routines that allow you to write client code in a traditional linear style, without idle procs, and to ask multiple questions of multiple servers simultaneously. And, even better, the Threads and AppleEvent managers do all of the hard work for you!
I first got interested in threaded AppleEvent code while working on a credit card validation server (Credit Now!, Appropriate Solutions). The intent was to develop a small application which could receive information about a purchase, dial up the credit card network, process the transaction and return an authorization code. Sending an AppleEvent seemed like the logical thing to do. The problem was that, with the phone call involved, the event took approximately 45 seconds to generate a reply. Further, during that time, we had to service the serial port, run a communication protocol which was best expressed as a loop, and service the user. (After all, no user would tolerate their machine locking up for 45 seconds.) This sounded like a good job for the then just-released Threads Manager. I’m not sure where I got the idea of spawning threads using AppleEvents, but I’m pretty sure it involved beer. Anyway, I’ve used the code in several products since and have been very happy with it.
A word about the code. One of my pet peeves with example code has been that handling errors is left as an exercise for the programmer. This is not the case with AEThreads and Futures. I’ve made every attempt to ensure that the libraries meet commercial quality code standards. While I must make all the usual disclaimers, I use this code in shipping products, so I’ll fix any bugs you report. I have provided the full source to offer you some insight into some nuances of threaded programming and to allow you advanced programmers out there to fine tune them. (I use slightly different versions to support TCL, MacApp, and PowerPlant exception handling.) Also, until Sprocket has a true Thread class (coming soon), you may want to edit the SwitchIn and SwitchOut routines to save additional context unique to your application.
You may also notice that this article makes no mention whatsoever (except in this paragraph) of preemptive threads, semaphores, critical sections or a number of other things you may have heard of in your operating systems class. This is intentional. This article and code are intended to save you time. Preemptive threads are not supported on the PowerPC. Having them in your system means you have to think about things like semaphores, resource contention, deadly embrace, etc. This does not save you time. Enough said.
So, without further ado, let’s get to the meat of the article.
AEThreads
The first thing you need to do to implement a multi-threaded server is figure out how to spawn a new thread. If you’ve been reading the Threads Manager documentation and Randy’s article last month, you know that to start a new thread, all you have to do is call NewThread(), right? How do you get parameters to it? How do you get results back? You dutifully pack up all the information into a big structure in a local variable and pass its address as the threadParam to NewThread. You pass the address of another variable as the threadResult parameter. But when you run your code, you discover, after many trips to Macsbug, that the routine that called NewThread() has long since returned by the time the thread actually runs (leaving threadParam and threadResult pointing into hyperspace). There’s got to be an easier way to get information to a thread.
Well, how about just sending it an AppleEvent? OK, a thread isn’t an application, so you can’t send an event to it directly, but using the AEThreads library you can send an event to yourself and have it handled by a thread. In fact, AEThreads has only one public routine - AEInstallThreadedEventHandler(). To use it, just call it where you would have called AEInstallEventHandler() to install your handler for the event. AEInstallThreadedEventHandler() takes the same parameters as AEInstallEventHandler (except isSysHandler, since we need our applications’s A5 world) plus the ThreadOptions and stack size parameters from NewThread. When an event comes in, AEThreads automatically suspends the event, creates a new thread and calls your handler from within it. When your handler returns, it cleans up, resumes the event, and returns the reply to the sender. Notice that if the Threads Manager is not present and you don’t do anything that requires multiple events to be handled simultaneously, you can just call AEInstallEventHandler() instead of AEInstallThreadedEventHandler() and your application will still run, except that incoming events will be handled synchronously.
Yielding
Now that we have all of our AppleEvents handled in separate threads - we’re done, right? Well, not quite. Recall that we’re running in a cooperative multitasking environment. This means that it is our responsibility to give CPU time to other threads; if we don’t, then our thread will finish synchronously, completely missing the advantage of using a thread to handle the event.
The Threads manager provides a number of routines for scheduling thread execution. The simplest of these is YieldToAnyThread(), which you can call at any time you think would be good to give someone else some CPU time. The important thing to note is that, unlike WaitNextEvent(), YieldToAnyThread() is a very inexpensive call, so you shouldn’t be afraid to call it often. (You should, however, have a thread-aware event loop, like the one Dave Falkenburg put into Sprocket, to make sure your main thread doesn’t call WaitNextEvent too often).
Blocking I/O
Another technique for yielding CPU time involves blocking I/O routines. These are routines which look like high level synchronous I/O routines, except that they know enough to block your thread and give up the CPU while the I/O is executing. For instance, a blocking version of FSRead() might look like this:
/* 1 */ pascal OSErr ThreadFSRead(short refNum,long *count,void *buffPtr, long timeout) { ParamBlockRec pb; pb.ioParam.ioCompletion = nil; pb.ioParam.ioRefNum = refNum; pb.ioParam.ioBuffer = buffPtr; pb.ioParam.ioReqCount = *count; pb.ioParam.ioPosMode = 0; pb.ioParam.ioPosOffset = 0; timeout += TickCount(); PBReadAsync(&pb); while (pb.ioParam.ioResult > 0 && TickCount() <= timeout) { YieldToAnyThread(); } *count = pb.ioParam.ioActCount; return pb.ioParam.ioResult; }
Now, replacing calls to FSRead() with ThreadFSRead() will allow other threads to execute while the I/O is in progress. We have also added a timeout mechanism which is useful for serial I/O. Note that this technique requires very little modification to existing code. Further, Apple promises to add blocking I/O to the Mac OS in the future. Writing your code in this way prepares you for the future. You may also notice that we didn’t use any of the fancy Thread Manager routines to suspend the thread, etc. This is because it is possible for the asynchronous I/O call to complete while we were trying to put the thread to sleep, leaving it stuck that way. While there are ways around this, it’s not worth the hassle. YieldToAnyThread() is cheap, and this technique gives a robust timeout mechanism for free. (If you didn’t understand that, don’t worry, you don’t need to).
It is important to note that, depending on the driver you’re calling, the call to PBReadAsync() may complete synchronously, resulting in no yield. This is true for floppy and pre-SCSI Manager 4.3 hard disk reads. In these cases you may want a more sophisticated routine which reads blocks, say 4k, yielding between each block. Also, in the case of the serial port, you may want to issue a control call first to see how many bytes are actually waiting. But these are topics for another article
Futures
One of the biggest hassles of writing AppleEvent-based client-server code (or any communications code in the Macintosh) is that you must rewrite any time-consuming algorithm into a state machine built around idle procs. This is because you must constantly service the event loop by calling WaitNextEvent(). This is tedious, time consuming, error prone, and generally not fun. If you’ve got some spare time you just really want to waste, try implementing the ZModem protocol this way.
Enter the Threads Manager. Now you can just spawn a thread, implement your algorithm as a series of nested loops (just like a “real” operating system), and sprinkle a few calls to YieldToAnyThread() through your code. This works great if you’re talking to a serial port, but what if you want to send AppleEvents to another application (or yourself) in the loop. Then you’re back to writing state machines. (Or some very complicated Apple Event idle procs)
In his article “Threaded Communication with Futures” in develop issue 7, Michael Gough described a particularly elegant solution to this problem, called the Futures Package, which provided a blocking I/O style interface to the AppleEvent manager based on the Threads Manager’s predecessor, the Threads Package. In fact, it goes even further by performing a kind of delayed evaluation which allows the client code to send events to multiple servers without waiting until it needs to use a reply which hasn’t returned yet. Unfortunately, support for the Futures Package was discontinued when the Threads Package was replaced by the Threads Manager. Apple even pulled the example code off the develop CD.
Last December I was talking to Brad Post and Eric Anderson about the Threads Manager at a PowerPC training session and asked what ever became of the Futures Package. I was told that, while it was really cool, nobody had gotten the time to update it and it didn’t look like it was going to happen any time soon. I begged. The next day Brad gave me some source that hadn’t been compiled yet to see if I could get it working. I promised to try. After a couple of late nights and some serious hair pulling trying to find a missing ThreadEndCritical(), (I later removed all the critical section code because the AppleEvent manager can’t be called at interrupt time and nobody else has any business looking at the data anyway) I got the package working. I give this long-winded explanation because the small amount of code you see here is the result of a lot of people’s work and I’m not entirely sure who gets credit for what, but the end result is extremely cool, elegant, and useful.
The key function in the Futures package is Ask(). Ask() functions like AESend(), except that it returns immediately. The trick is that its reply AppleEvent is actually a future (or thunk to you Scheme programmers, and to resolve Randy’s dangling pun from last month). As long as you don’t attempt to extract any data from it, your code continues to execute normally. However, if you try to extract information (using AEGetParamPtr() or any of its friends) before the reply has actually returned, the Futures library will suspend execution of your thread until the reply actually returns. The result is that, to your thread, it looks like AEGetParamPtr() returned immediately too, but in fact the CPU was transparently given to other tasks until your request could be fulfilled. Important: If you want to be able to process incoming events during a call to Ask(), make sure you’re not calling it from the main thread. This is what AEThreads is designed to help you do - just install your server routine as a threaded handler.
Disclaimer
You may discover, after reading the code, that the functionality of the Futures library really belongs in the AppleEvent manager. It does. In fact, I believe that adding kAEFutureReply as a send mode in AESend() would take care of it at the API level. (Is anyone at Apple listening?) The source code is provided here because I cannot guarantee that it is entirely bug free. However, you should be very cautious in modifying it. It uses a pair of special handlers in the AppleEvent manager which were added to support the original futures package; they’re not documented for third-party use, and I strongly urge that you not use them for anything else. There is also a design limitation if the reply to your event is never received (because of a lost network connection or some other reason) you will not get a timeout error and your thread will stay suspended indefinitely. I plan to fix this in the future, and it may not be a big problem in many cases, but please be aware of it. If anyone out there wants to add this functionality, I will gladly include it in a future release.
/* 2 */ AEThreads Reference AEInstallThreadedEventHandler pascal OSErr AEInstallThreadedEventHandler( AEEventClass theAEEventClass, AEEventID theAEEventID, AEEventHandlerProcPtr handler, long handlerRefcon, ThreadOptions options, Size stacksize);
AEInstallThreadedEventHandler is used to install a handler for an AppleEvent which is to be handled in a thread. The first four parameters are the same as for AEInstallEventHandler(), the last two are passed to NewThread() to create a thread for your handler. You may use any of the parameters documented in the threads manager except kNewSuspend (which would cause your handler to never be called).
Futures Reference
For a full description of the futures library, see Michael Gough’s develop article. A quick summary is provided here for your convenience.
InitFutures
/* 3 */ pascal OSErr InitFutures(void);
Call InitFutures() once at the beginning of your program to initialize the futures package.
Ask
/* 4 */ pascal OSErr Ask(AppleEvent* question, AppleEvent* answer);
Call Ask() instead of AESend() to send an AppleEvent. The trick to efficient code is to call Ask() as early as possible and look at the result as late as possible in order to give the server the maximum amount to time to process your request.
IsFuture
/* 5 */ pascal Boolean IsFuture(AppleEvent* message);
Call IsFuture() to test if the reply from a call to Ask() is a future without stopping your thread if it is. If IsFuture() returns true, the reply hasn’t returned yet and you should probably go work on something else.
BlockUntilReal
/* 6 */ pascal OSErr BlockUntilReal(AppleEvent* message);
Call BlockUntilReal() to force the current thread to block until the reply actually comes back.
How AEThreads Works
The AEThreads library is implemented as a chain of three main routines (AEInstallThreadedEventHandler(), SpawnAEThread() and AEThread()) and a pair of custom thread switchers.
AEInstallThreadedEventHandler() is a fairly simple routine. Basically, it allocates a pointer in the application heap, copies its parameters there and calls AEInstallEventHandler() for the event specified with SpawnAEThread() as the handler and the pointer as the refcon.
When an event comes in, SpawnAEThread() is invoked. Its responsibility is to get the new thread started. First, it copies the parameters needed by the new thread into a local structure and then calls NewThread() with AEThread() as the threadProc and the address of the parameter structure as the threadParam. Next it enters a yield loop, yielding the thread it just created and watching a flag in the parameter block for a signal that the thread has started. This is necessary because, although the thread has been created, the threadProc hasn’t been called yet and the thread parameters are in a local variable. If we returned to the AppleEvent manager now, the threadParam would be a dangling pointer when the thread actually ran. This can also be avoided by allocating the threadParam as a pointer or handle. I have chosen not to do this here, however, because I don’t want to fragment the heap more than necessary and the semaphore structure allows us to get an error message from the threadProc if it has difficulty getting itself up and running. (OK, I mentioned semaphore again, but at least you didn’t have to deal with it).
AEThread() is the wrapper routine which actually calls your handler. The first thing it does is copy its parameters into local variables so they’ll still be around when SpawnAEThread() returns. Next it installs a pair custom switcher which saves and restore any global context unique to used to our thread. Metrowerks C++ stores a linked list of stack-based object whose destructors must be called in compiler-generated global variable __local_destructor_chain. You must save and restore it here or you will be very sorry. Also if you are using a class library with exception handling, you would save and restore the failure stack here (gTopHandler for MacApp; gTopHandler, gLastError, and gLastMessage for TCL 1.x). You may also want to save thePort, etc. This is necessary so that if a failure occurs in the thread, no handlers from outside the thread will be called. Now we suspend the event, clear the semaphore, and enter a yield loop so SpawnAEThread() can return to the AppleEvent manager.
The next time we get time, we are on our own. We now call the user’s handler, wrapped in a failure handler, if available. If an error is reported here, we must manually pack the error code into the reply AppleEvent before returning. Next we resume the event and return to the Apple Event Manager. This will let the thread die and cause the reply event to be returned to the sender.
OK, it’s a little confusing, but just remember that it was done here so you won’t have to
How Futures Works
The futures code is based around two undocumented (until now) callbacks in the AppleEvent manager which are accessed via AEInstallSpecialHandler(). One (‘blck’) [Randy, can we get these puppies some real names] is called whenever there is an attempt to read data from a reply event which hasn’t arrived yet. The other ‘unbk’ is called whenever a reply arrives. We also use the refcon (‘refc’) attribute of the event to store a handle to a list of the threads currently waiting on a reply for this event.
InitFutures() simply installs DoThreadBlock() and DoThreadUnBlock() as the ‘blck’ and ‘unbk’ handlers, respectively.
If someone tries to extract data from a reply which is really a future, DoThreadBlock() is called by the AppleEvent manager. DoThreadBlock() then checks the ‘refc’ attribute of the event for a list of blocked threads. If it finds one, it adds the current thread to it; otherwise it creates a new list containing the current thread and puts it back in the reply. In either case it then suspends the thread which caused it to be called.
Whenever an incoming reply is detected, DoThreadUnBlock() is called for the event. If the refcon of the event contains a blocked thread list, DoThreadUnBlock() makes all of the threads in the list eligible for execution.
Ask() is simply a wrapper which calls AESend() synchronously with a timeout of 0 ticks, causing it to time out immediately and suppresses the timeout error. The reply will eventually come in, however, and be properly reported.
IsFuture() temporarily replaces DoThreadBlock() with a handler which does nothing and tests for a errAEReplyNotArrived error.
BlockUntilReal() just tries to extract a nonexistent parameter, ‘gag!’, from the event, forcing a block if the reply isn’t real.
The Sample Code
The demo works as follows: Selecting “Ping” from the Debug menu sends an AppleEvent back to the application which calls the HandlePing() function in a thread. It brings up a PPCBrowser window asking you to select this or another copy of Sprocket as a target. It then enters a loop sending ping events to the target. For each ping, the target extracts the direct object from the event, stuffs in a reply and beeps to let you know it’s doing its job. Selecting Ping2 does the same thing, but lets you choose two separate targets.
To see how this all works, take a look at the latest version of Sprocket and check out the files AEThreads.h and .c, Futures.h and .c, and FuturesDemo.h and.c. FuturesDemo.h is excerpted from Michael’s develop sample code, updated to use AEThreads. There are also a few lines added to App.cp to set up the libraries and add menu handlers.
In Conclusion...
Well, that’s about it. I hope both this article and the code are useful to you. In the future, I would like to continue to add technology to Sprocket. The next logical candidates are a simple Thread class, and an exception library (the other thing I can’t live without). It’s 3am and there’s too much blood in my caffeine system, so good night...
AEThreads.h
/* 7 */ // AEThreads.h // // Copyright © 1993-94 Steve Sisak // // License is granted to use, modify, make derivative works, and // duplicate this code at will, so long as this notice remains intact. // #ifndef __AETHREADS__ #include "AEThreads.h" #endif #ifndef __ERRORS__ #include <Errors.h> #endif #ifndef __APPLEEVENTS__ #include <AppleEvents.h> #endif #if __MWERKS__ #if defined(powerc) || defined(__powerc) #include <CPlusLibPPC.h> #else #include <stdlib.h> #include <CPlusLib68k.h> #endif #endif typedef struct AEThreadDesc AEThreadDesc; typedef struct AEThreadParam AEThreadParam; typedef struct AESwapData AESwapData; struct AEThreadDesc// Kept in the OS refcon { AEEventHandlerUPP handler; // The real handler long refcon; // The real refcon Size stackSize; // Stack size for handling event ThreadOptions options; // Thread options for event ThreadID holder;// used as a semaphore }; struct AEThreadParam // Used in spawning { const AppleEvent* event; AppleEvent*reply; AEThreadDesc* desc; ThreadID thread; OSErr result; }; struct AESwapData { void* fTopHandler; // Top failure handler #ifdef __MWERKS__ DestructorChain*fStaticChain;// #endif }; pascal void SwitchInHandler(ThreadID threadBeingSwitched, void *switchProcParam); pascal void SwitchOutHandler(ThreadID threadBeingSwitched, void *switchProcParam); pascal OSErrSpawnAEThread(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon); pascal long AEThread(AEThreadParam* parms); AEEventHandlerUPP gSpawnAEThreadUPP = nil; #pragma segment foobar AEInstallThreadedEventHandler pascal OSErr AEInstallThreadedEventHandler( AEEventClass theAEEventClass, AEEventIDtheAEEventID, AEEventHandlerUPP proc, long handlerRefcon, ThreadOptions options, Size stacksize) { AEThreadDesc* desc = (AEThreadDesc*) NewPtr(sizeof(AEThreadDesc)); OSErr err = MemError(); if (gSpawnAEThreadUPP == nil) { gSpawnAEThreadUPP = NewAEEventHandlerProc(SpawnAEThread); } if (err == noErr) { desc->handler = proc; desc->refcon = handlerRefcon; desc->stackSize = stacksize; desc->options = options; desc->holder = kNoThreadID; err = AEInstallEventHandler(theAEEventClass, theAEEventID, gSpawnAEThreadUPP, (long) desc, false); } return err; } #pragma segment AEThread SwitchInHandler pascal void SwitchInHandler(ThreadID threadBeingSwitched, void *switchProcParam) { AESwapData* swap = (AESwapData*) switchProcParam; #ifdef __MWERKS__ swap->fStaticChain = __local_destructor_chain; #endif } SwitchOutHandler pascal void SwitchOutHandler(ThreadID threadBeingSwitched, void *switchProcParam) { AESwapData* swap = (AESwapData*) switchProcParam; #ifdef __MWERKS__ __local_destructor_chain = swap->fStaticChain; #endif } #define ErrCheck(label, result) if ((result) != noErr) goto label; AEThread pascal long AEThread(AEThreadParam* parms) { AppleEvent event; // Original parameters we care about AppleEvent reply; AEThreadDesc * desc; OSErr err; OSErr procErr; AESwapData swap; event = *parms->event; // copy these into our own stack frame reply = *parms->reply; desc = parms->desc; #if 0 myTopHandler = gTopHandler;// Save global failure handler gTopHandler = nil; // don’t let failures propagate outside #endif ErrCheck(punt, err = SetThreadSwitcher(kCurrentThreadID, SwitchInHandler, &swap, true)); ErrCheck(punt, err = SetThreadSwitcher(kCurrentThreadID, SwitchOutHandler, &swap, false)); ErrCheck(punt, err = AESuspendTheCurrentEvent(&event)); parms->result = noErr; // Let caller know we’re ready // At this point, we need to let our caller return while (desc->holder != kNoThreadID) { YieldToThread(desc->holder); } // We are now on our own procErr = err = CallAEEventHandlerProc(desc->handler, &event, &reply, desc->refcon); // Since the event was suspended, we need to stuff the error code ourselves // note that there’s not much we can do about reporting errors beyond here err = AEPutAttributePtr(&reply, keyErrorNumber, typeShortInteger, &procErr, sizeof(procErr)); #if qDebug if (err) ProgramBreak("\pAEPutAttributePtr failed installing error code - very bad"); #endif err = AEResumeTheCurrentEvent(&event, &reply, kAENoDispatch, 0);// This had better work #if qDebug if (err) DebugStr("\pAEResumeTheCurrentEvent failed - very bad"); #endif #if 0 gTopHandler = myTopHandler;// Restore global failure handler myTopHandler = nil; // Keep terminator from firing handlers #endif punt: parms->result = err; return nil; } #pragma segment Spawn SpawnAEThread pascal OSErr SpawnAEThread(const AppleEvent *event, AppleEvent *reply, long handlerRefcon) { AEThreadParam param; param.event = event; param.reply = reply; param.desc = (AEThreadDesc*) handlerRefcon; param.thread = kNoThreadID; if (!param.desc) { param.result = paramErr; } else { // make sure no-one else is trying to start a handler while (param.desc->holder != kNoThreadID) { YieldToAnyThread(); } if ((param.result = GetCurrentThread(¶m.desc->holder)) == noErr) // Grab the semaphore { param.result = NewThread(kCooperativeThread, (ThreadEntryProcPtr) &AEThread, ¶m, param.desc->stackSize, param.desc->options, nil, ¶m.thread); if (param.result == noErr) { param.result = 1; do { YieldToThread(param.thread); } while (param.result == 1); // Wait for thread // to pick up parameters } } param.desc->holder = kNoThreadID; // release any claims we have } return param.result; }
Futures.c
/* 8 */ /* File: Futures.c Copyright: © 1993 by Apple Computer, Inc., all rights reserved. © 1993-1994 by Steve Sisak, all rights reserved. */ #include "Futures.h" #include <Threads.h> #include <GestaltEqu.h> pascal OSErrIsFutureBlock(AppleEvent* message); pascal OSErrDoThreadBlock(AppleEvent* message); pascal OSErrDoThreadUnblock(AppleEvent* message); #define kAERefconAttribute'refc' #define kAENonexistantAttribute 'gag!' #define kImmediateTimeout 0 struct ThreadList { short numThreads; ThreadID threads[1]; }; typedef struct ThreadList ThreadList, *ThreadListPtr, **ThreadListHdl; #define sizeofThreadList(numthreads) \ (sizeof(ThreadList) + ((numthreads)-1)*sizeof(ThreadID)) typedef pascal OSErr (*AESpecialHandlerProcPtr) (AppleEvent *theAppleEvent); enum { uppAESpecialHandlerProcInfo = kPascalStackBased | RESULT_SIZE(SIZE_CODE(sizeof(OSErr))) | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(AppleEvent*))) }; #if USESROUTINEDESCRIPTORS typedef UniversalProcPtr AESpecialHandlerUPP; #define CallAESpecialHandlerProc(userRoutine, \ theAppleEvent, reply, handlerRefcon)\ CallUniversalProc((UniversalProcPtr)(userRoutine), \ uppAESpecialHandlerProcInfo, (theAppleEvent), \ (reply), (handlerRefcon)) #define NewAESpecialHandlerProc(userRoutine) \ (AESpecialHandlerUPP)NewRoutineDescriptor( \ (ProcPtr)(userRoutine), \ uppAESpecialHandlerProcInfo, GetCurrentISA()) #else //typedef AESpecialHandlerProcPtr AESpecialHandlerUPP; typedef ProcPtr AESpecialHandlerUPP; #define CallAESpecialHandlerProc(userRoutine, \ theAppleEvent, reply, handlerRefcon)\ (*(userRoutine))((theAppleEvent), (reply), (handlerRefcon)) #define NewAESpecialHandlerProc(userRoutine) \ (AESpecialHandlerUPP)(userRoutine) #endif AESpecialHandlerUPP gDoThreadBlockUPP= nil; AESpecialHandlerUPP gDoThreadUnblockUPP= nil; AESpecialHandlerUPP gIsFutureBlockUPP= nil; InitFutures pascal OSErr InitFutures(void) { OSErr err; long aResponse; gDoThreadBlockUPP = NewAESpecialHandlerProc(DoThreadBlock); gDoThreadUnblockUPP = NewAESpecialHandlerProc(DoThreadUnblock); gIsFutureBlockUPP = NewAESpecialHandlerProc(DoThreadBlock); err = Gestalt(gestaltThreadMgrAttr, &aResponse); if (err == noErr) err = AEInstallSpecialHandler('blck', gDoThreadBlockUPP, false); if (err == noErr) err = AEInstallSpecialHandler('unbk', gDoThreadUnblockUPP, false); return err; } DoThreadBlock pascal OSErr DoThreadBlock(AppleEvent* message) { OSErr err; DescType actualType; Size actualSize; ThreadListHdl threadList; ThreadID currentThread; //Apparently the current thread needs to access some information, which //is really a future. We need to see if there is already a list of threads //blocked on this message. If there isn’t, create an empty list. Add //the current thread to the list. Sleep the current thread. err = GetCurrentThread(¤tThread); if (err == noErr) { err = AEGetAttributePtr(message, kAERefconAttribute, typeLongInteger, &actualType, (Ptr) &threadList, sizeof(threadList), &actualSize); if (err == errAEDescNotFound || err == noErr && !threadList) { // If we can’t find a waiting thread list, then create one containing // just ourself and put it back in the message threadList = (ThreadListHdl) NewHandle(sizeofThreadList(1)); err = MemError(); if (err == noErr) { (**threadList).numThreads = 1; (**threadList).threads[0] = currentThread; err = AEPutAttributePtr(message, kAERefconAttribute, typeLongInteger, (Ptr) &threadList, sizeof(threadList)); } } else if (err == noErr) { // Otherwise just append ourself onto the existing list short numWaiting = (**threadList).numThreads; SetHandleSize((Handle) threadList, sizeofThreadList(numWaiting+1)); err = MemError(); if (err == noErr) { (**threadList).threads[numWaiting] = currentThread; (**threadList).numThreads = ++numWaiting; } } } // If there was an error don’t block if (err == noErr) err = SetThreadState(currentThread, kStoppedThreadState, kNoThreadID); return err; } DoThreadUnblock pascal OSErr DoThreadUnblock(AppleEvent* message) { OSErr err; DescType actualType; Size actualSize; ThreadStateblockedThreadState; ThreadListHdl threadList; //This message has just turned real. If there is a list of threads blocked //because they tried to access the data, walk through the list of blocked //threads waking and deallocating the list element as you go. err = AEGetAttributePtr(message, kAERefconAttribute, typeLongInteger, &actualType, (Ptr) &threadList, sizeof(threadList), &actualSize); if (err == errAEDescNotFound) { //It’s possible that this unblocking handler will get called for ALL replies //to apple events, not just futures. If that’s the case, then getting //the above error is not really an error. Clear it and just return. err = noErr; } else if (err == noErr && threadList) { //If there’s a waiting list, make all threads in it ready for execution //We won’t report errors inside the loop because: //1) one of the threads might have been disposed of //2) there’s nothing we can do to recover at this point //3) the important thing is to wake up all remaining threads. ThreadID*nextThread = (**threadList).threads; short numWaiting = (**threadList).numThreads; while (--numWaiting >= 0) { ThreadID blockedThread = *nextThread++; OSErr err1 = GetThreadState(blockedThread, &blockedThreadState); if (err1 == noErr && blockedThreadState == kStoppedThreadState) { err1 = SetThreadState(blockedThread, kReadyThreadState, kNoThreadID); } } // Now free the list handle (and take it out of the refCon just to be safe) DisposeHandle((Handle) threadList); threadList = nil; err = AEPutAttributePtr(message, kAERefconAttribute, typeLongInteger, (Ptr) &threadList, sizeof(threadList)); } return err; } BlockUntilReal pascal OSErr BlockUntilReal(AppleEvent* message) { OSErr err; AERecord nonExistentParameter; err = AEGetParamDesc(message, kAENonexistantAttribute, typeAERecord, &nonExistentParameter); if (err == errAEDescNotFound) err = noErr; return err; } IsFuture pascal Boolean IsFuture(AppleEvent* message) { OSErr err; AESpecialHandlerUPP oldBlockingProc; BooleanisFuture = false; err = AEGetSpecialHandler('blck', &oldBlockingProc, false); if (err == noErr) { err = AEInstallSpecialHandler('blck', gIsFutureBlockUPP, false); if (err == noErr) { if (BlockUntilReal(message) == errAEReplyNotArrived) { isFuture = true; } err = AEInstallSpecialHandler('blck', oldBlockingProc, false); } } return isFuture; } IsFutureBlock pascal OSErr IsFutureBlock(AppleEvent* /*message*/) { return noErr; } Ask pascal OSErr Ask(AppleEvent* question, AppleEvent* answer) { //Send the question with an immediate timeout. OSErr err = AESend(question, answer, kAEWaitReply, kAENormalPriority, kImmediateTimeout, nil, nil); if (err == errAETimeout) err = noErr; return err; }
- SPREAD THE WORD:
- Slashdot
- Digg
- Del.icio.us
- Newsvine