TweetFollow Us on Twitter

Sprocket Threads
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.


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.


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.


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 
 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();


 while (pb.ioParam.ioResult > 0 && TickCount() <= timeout)

 *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


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.


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


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.


/* 3 */
pascal OSErr InitFutures(void);

Call InitFutures() once at the beginning of your program to initialize the futures package.


/* 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.


/* 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.


/* 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...


/* 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"
#ifndef __ERRORS__
#include <Errors.h>
#ifndef __APPLEEVENTS__
#include <AppleEvents.h>
#if __MWERKS__
#if defined(powerc) || defined(__powerc)
#include <CPlusLibPPC.h>
#include <stdlib.h>
#include <CPlusLib68k.h>

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;
 AEThreadDesc*   desc;
 ThreadID thread;
 OSErr  result;

struct AESwapData
 void*  fTopHandler; // Top failure handler

#ifdef __MWERKS__

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


pascal OSErr AEInstallThreadedEventHandler(
 AEEventClass    theAEEventClass,
 AEEventHandlerUPP proc,
 long   handlerRefcon,
 ThreadOptions   options,
 Size   stacksize)
 AEThreadDesc* desc = (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


pascal void SwitchInHandler(ThreadID threadBeingSwitched, void *switchProcParam)
 AESwapData* swap = (AESwapData*) switchProcParam;

#ifdef __MWERKS__
 swap->fStaticChain = __local_destructor_chain;


pascal void SwitchOutHandler(ThreadID threadBeingSwitched, void *switchProcParam)
 AESwapData* swap = (AESwapData*) switchProcParam;

#ifdef __MWERKS__
 __local_destructor_chain = swap->fStaticChain;

#define ErrCheck(label, result)  if ((result) != noErr) goto label;


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

 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)

 // 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 
 err = AEPutAttributePtr(&reply, keyErrorNumber, 
 typeShortInteger, &procErr, 

#if qDebug
 if (err)
 ProgramBreak("\pAEPutAttributePtr failed installing error code - very 

 err = AEResumeTheCurrentEvent(&event, &reply,
 kAENoDispatch, 0);// This had better work

#if qDebug
 if (err)
 DebugStr("\pAEResumeTheCurrentEvent failed - very bad");

#if 0
 gTopHandler = myTopHandler;// Restore global failure handler
 myTopHandler = nil; // Keep terminator from firing handlers

 parms->result = err;
 return nil;

#pragma segment Spawn


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;
 // make sure no-one else is trying to start a handler   
 while (param.desc->holder != kNoThreadID)   
 if ((param.result = 
 GetCurrentThread(&param.desc->holder)) == noErr)
 // Grab the semaphore
 param.result = NewThread(kCooperativeThread,
 (ThreadEntryProcPtr) &AEThread,
 if (param.result == noErr)
 param.result = 1;
 while (param.result == 1); // Wait for thread 
 // to pick up parameters
 param.desc->holder = kNoThreadID; // release any claims we have
 return param.result;


/* 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
  | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(AppleEvent*)))

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())
//typedef AESpecialHandlerProcPtr AESpecialHandlerUPP;
typedef ProcPtr AESpecialHandlerUPP;

#define CallAESpecialHandlerProc(userRoutine,      \
 theAppleEvent, reply, handlerRefcon)\
 (*(userRoutine))((theAppleEvent), (reply), (handlerRefcon))
#define NewAESpecialHandlerProc(userRoutine)       \

AESpecialHandlerUPP gDoThreadBlockUPP= nil;
AESpecialHandlerUPP gDoThreadUnblockUPP= nil;
AESpecialHandlerUPP gIsFutureBlockUPP= nil;

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,
 if (err == noErr)
 err = AEInstallSpecialHandler('unbk', 
 gDoThreadUnblockUPP, false);

 return err;


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 
 //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(&currentThread);

 if (err == noErr)
 err = AEGetAttributePtr(message, kAERefconAttribute,
 typeLongInteger, &actualType,
 (Ptr) &threadList, sizeof(threadList), 

 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, 
 (Ptr) &threadList, sizeof(threadList));
 else if (err == noErr)
 // Otherwise just append ourself onto the existing list
 short numWaiting = (**threadList).numThreads;
 SetHandleSize((Handle) threadList, 
 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, 

 return err;


pascal OSErr DoThreadUnblock(AppleEvent* message)
 OSErr  err;
 DescType actualType;
 Size   actualSize;
 ThreadListHdl   threadList;

 //This message has just turned real.  If there is a list of threads 
 //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), 
 if (err == errAEDescNotFound)
 //It’s possible that this unblocking handler will get called for ALL 
 //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,
 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 
 DisposeHandle((Handle) threadList);
 threadList = nil;
 err = AEPutAttributePtr(message, kAERefconAttribute,
 (Ptr) &threadList, sizeof(threadList));


 return err;


pascal OSErr BlockUntilReal(AppleEvent* message)
 OSErr  err;
 AERecord nonExistentParameter;
 err = AEGetParamDesc(message, kAENonexistantAttribute,
        typeAERecord, &nonExistentParameter);

 if (err == errAEDescNotFound)
 err = noErr;
 return err;


pascal Boolean IsFuture(AppleEvent* message)
 OSErr  err;
 AESpecialHandlerUPP oldBlockingProc;
 BooleanisFuture = false;
 err = AEGetSpecialHandler('blck', &oldBlockingProc, false);
 if (err == noErr)
 err = AEInstallSpecialHandler('blck', gIsFutureBlockUPP,
 if (err == noErr)
 if (BlockUntilReal(message) == errAEReplyNotArrived)
 isFuture = true;
 err = AEInstallSpecialHandler('blck', oldBlockingProc,
 return isFuture;


pascal OSErr IsFutureBlock(AppleEvent* /*message*/)
 return noErr;


pascal OSErr Ask(AppleEvent* question, AppleEvent* answer)
 //Send the question with an immediate timeout.

 OSErr err = AESend(question, answer, kAEWaitReply,
        kImmediateTimeout, nil, nil);
 if (err == errAETimeout)
 err = noErr;

 return err;


Community Search:
MacTech Search:

Software Updates via MacUpdate

Skype - Voice-over-internet ph...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
PushPal 3.0 - Mirror Android notificatio...
PushPal is a client for Pushbullet, which automatically shows you all of your phone's notifications right on your computer. This means you can see who's calling or read text messages even if your... Read more
Logic Pro X 10.1.1 - Music creation and...
Apple Logic Pro X is the most advanced version of Logic ever. Sophisticated new tools for professional songwriting, editing, and mixing are built around a modern interface that's designed to get... Read more
VLC Media Player 2.2.0 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Sound Studio 4.7.8 - Robust audio record...
Sound Studio lets you easily record and professionally edit audio on your Mac. Easily rip vinyls and digitize cassette tapes, or record lectures and voice memos. Prepare for live shows with live... Read more
LibreOffice - Free, open-source...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
VueScan 9.5.03 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Freeway Pro 7.0.3 - Drag-and-drop Web de...
Freeway Pro lets you build websites with speed and precision... without writing a line of code! With its user-oriented drag-and-drop interface, Freeway Pro helps you piece together the website of... Read more
Cloud 3.3.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more
Cyberduck 4.6.5 - FTP and SFTP browser....
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more

The first ever action 3D card battler Al...
On the other hand, you probably haven’t played an action 3D card battler – until now. Step forward, All Star Legion. All Star Legion is a 3D QTE-based action RPG card battler, but fear not – the game itself isn’t as convoluted as its description.... | Read more »
Travel Back to the 1980s With the Making...
Headup Games has released a hilarious making of video for its upcoming title, Pixel Heroes: Byte & Magic. The game is a RPG/Roguelike where you control three heroes set to save the township of Pixton from an evil cult called The Sons of Dawn.... | Read more »
Heavenstrike Rivals Review
Heavenstrike Rivals Review By Campbell Bird on March 2nd, 2015 Our Rating: :: HEAVENLY STRATEGICUniversal App - Designed for iPhone and iPad Despite a few flaws, this free-to-play strategy game is a fun mix of new and old strategy... | Read more »
Get The Whole Story – Lone Wolf Complete...
Get The Whole Story – Lone Wolf Complete is Now Available and On Sale Posted by Jessica Fisher on February 27th, 2015 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Who Wore it Best? The Counting Dead vs....
Like it or not, the “clicker” genre, popularized by cute distractions like Candy Box and Cookie Clicker, seems like it’s here to stay. So Who Wore it Best? takes a look at two recent examples: The Counting Dead and AdVenture Capitalist. | Read more »
Card Crawl, the Mini Deck Building Game,...
Card Crawl, the Mini Deck Building Game, is Coming Soon Posted by Jessica Fisher on February 27th, 2015 [ permalink ] Tinytouchtales and Mexer have announced their new game, | Read more »
Witness an all new puzzle mechanic in Bl...
Well, BlastBall MAX is not one of those games and is bucking trends such as timers, elements of randomness, and tacked-on mechanics in favor of pure puzzle gameplay. When you first boot up the game you’ll see a grid made up of squares that are each... | Read more »
This Princess Has a Dragon and She isn’t...
This Princess Has a Dragon and She isn’t Afraid to Useit. | Read more »
Mecha Showdown Review
Mecha Showdown Review By Lee Hamlet on February 27th, 2015 Our Rating: :: IN A SPINUniversal App - Designed for iPhone and iPad Mecha Showdown replaces traditional buttons with a slot machine mechanic in this robot fighting game,... | Read more »
Reliance Games and Dreamworks Unveil Rea...
Reliance Games and Dreamworks Unveil Real Steel Champions Posted by Ellis Spice on February 27th, 2015 [ permalink ] Reliance Games and Dreamworks have announced that a third game in | Read more »

Price Scanner via

27-inch 3.5GHz 5K iMac in stock today and on...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more
Apple Launches Free Web-Based Pages and Other...
Apple’s new Web-only access to iWork productivity apps is a free level of iCloud service available to anyone, including people who don’t own or use Apple devices. The service includes access to Apple... Read more
Survey Reveals Solid State Disk (SSD) Technol...
In a recent SSD technology use survey, Kroll Ontrack, a firm specializing in data recovery, found that while nearly 90 percent of respondents leverage the performance and reliability benefits of SSD... Read more
Save up to $600 with Apple refurbished Mac Pr...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
Apple CEO Tim Cook to Deliver 2015 George Was...
Apple CEO Tim Cook will deliver the George Washington University’s Commencement address to GWU grads on May 17, at which time he will also be awarded an honorary doctorate of public service from the... Read more
Apple restocks refurbished Mac minis for up t...
The Apple Store has restocked Apple Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz... Read more
Save up to $50 on iPad Air 2s, NY tax only, f...
 B&H Photo has iPad Air 2s on sale for $50 off MSRP including free shipping plus NY sales tax only: - 16GB iPad Air 2 WiFi: $469.99 $30 off - 64GB iPad Air 2 WiFi: $549 $50 off - 128GB iPad Air 2... Read more
16GB iPad Air 2 on sale for $447, save $52
Walmart has the 16GB iPad Air 2 WiFi on sale for $446.99 on their online store for a limited time. Choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
iMacs on sale for up to $205 off MSRP
B&H Photo has 21″ and 27″ iMacs on sale for up to $205 off MSRP including free shipping plus NY sales tax only: - 21″ 1.4GHz iMac: $1029 $70 off - 21″ 2.7GHz iMac: $1199 $100 off - 21″ 2.9GHz... Read more

Jobs Board

Sr. Technical Services Consultant, *Apple*...
**Job Summary** Apple Professional Services (APS) has an opening for a senior technical position that contributes to Apple 's efforts for strategic and transactional Read more
Event Director, *Apple* Retail Marketing -...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global engagement strategy and team. Delivering an overarching brand Read more
*Apple* Pay - Site Reliability Engineer - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.