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

GraphicConverter 11.2.2 - $39.95
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more
VueScan 9.7.30 - 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
Things 3.12.6 - Elegant personal task ma...
Things is a task management solution that helps to organize your tasks in an elegant and intuitive way. Things combines powerful features with simplicity through the use of tags and its intelligent... Read more
Skim 1.5.11 - PDF reader and note-taker...
Skim is a PDF reader and note-taker for OS X. It is designed to help you read and annotate scientific papers in PDF, but is also great for viewing any PDF file. Skim includes many features and has a... Read more
Navicat Premium Essentials 15.0.20 - Pro...
Navicat Premium Essentials is a compact version of Navicat which provides basic and necessary features you will need to perform simple administration on a database. It supports the latest features... Read more
Affinity Photo 1.8.4 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
EtreCheck Pro 6.3 - For troubleshooting...
EtreCheck is an app that displays the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support Communities to... Read more
beaTunes 5.2.11 - Organize your music co...
beaTunes is a full-featured music player and organizational tool for music collections. How well organized is your music library? Are your artists always spelled the same way? Any R.E.M. vs REM?... Read more
Bookends 13.4.4 - Reference management a...
Bookends is a full-featured bibliography/reference and information-management system for students and professionals. Bookends uses the cloud to sync reference libraries on all the Macs you use.... Read more
Affinity Designer 1.8.4 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more

Latest Forum Discussions

See All

Global Spy is an intriguing 2D spy sim f...
Developer Yuyosoft Innovations' Global Spy launched last month for iOS and Android, though if you missed it at the time, we're here to tell you why it's well worth a go. This one's all about international espionage, tracking down elusive spies,... | Read more »
Distract Yourself With These Great Mobil...
There’s a lot going on right now, and I don’t really feel like trying to write some kind of pithy intro for it. All I’ll say is lots of people have been coming together and helping each other in small ways, and I’m choosing to focus on that as I... | Read more »
Hyena Squad is sci-fi turn-based strateg...
Wave Light Games has just revealed its latest release, Hyena Squad, a turn-based RPG set in a space station infested by gross aliens and the living dead. The announcement was first reported on by Touch Arcade. [Read more] | Read more »
Idle Guardians: Never Die is a pixel art...
SuperPlanet has been fairly prolific with game releases so far this year with both Evil Hunter Tycoon and Lucid Adventure releasing earlier this year. Now, they've released another idle RPG called Idle Guardians: Never Die, which you can download... | Read more »
Ruinverse, Kemco's latest RPG, now...
Kemco's latest RPG endeavour, Ruinverse, initially launched for both iOS and Android earlier this month. It was released as a premium title that also had additional in-app purchases. Now, the developers have decided to release a freemium version... | Read more »
The 5 Best Mobile Platformers
Touch screens and action-oriented gameplay don't typically mix, but over the course of pondering the best platformers on mobile, I found myself having a really hard time picking just five. Quite a few developers have found really creative ways to... | Read more »
Clash Royale: The Road to Legendary Aren...
Supercell recently celebrated its 10th anniversary and their best title, Clash Royale, is as good as it's ever been. Even for lapsed players, returning to the game is as easy as can be. If you want to join us in picking the game back up, we've put... | Read more »
Endless runner Monster Dash will relaunc...
Remember Monster Dash? Well, it's set to return to a mobile device near you after having been pulled from stores in 2017 to meet GDPR compliance. This one first launched all the way back in August of 2010. Over ten years later, it's heading into... | Read more »
Auto Battle Chess is a colourful genre s...
Auto Battle Chess is an interesting hodgepodge of genres that aims to offer the ultimate auto chess experience. That's a pretty tall order, though with the game now out for Android, I suppose we don't have to wait to see if it lives up to its... | Read more »
Tom and Jerry: Chase hits 1 million pre-...
NetEase's 1v4 asymmetrical multiplayer game Tom and Jerry: Chase recently became available to pre-order for both iOS and Android in Southeast Asia. It's clearly proving to be a highly anticipated title too since it has now reached 1 million pre-... | Read more »

Price Scanner via

Expercom offers $320 discount on the 6-core 1...
Apple reseller Expercom has the Silver 16″ 6-core MacBook Pro on sale for a limited time for $2079 shipped. Their price is $320 off Apple’s MSRP for this model, and it’s the cheapest price currently... Read more
Apple announces Education pricing for new 202...
Purchase a new 2020 iMac or iMac Pro at Apple using Apple’s Education discount, and take up to $400 off MSRP. All teachers, students, and staff of any educational institution with a .edu email... Read more
Apple reseller Expercom offers $256 discount...
Expercom has Apple’s new 2020 10-core iMac Pro available for order and on sale for $4743 shipped. Their price is $256 off Apple’s MSRP for this new model, and it’s the cheapest price we’ve seen so... Read more
Apple releases refreshed 2020 27″ iMacs with...
Apple today released updated versions of their 27″ iMacs featuring 10th generation Intel processors, SSDs across the board, a better 5K display, and improvements to the camera, speakers, and mic.... Read more
Xfinity Mobile promo: Take $200-$350 off Appl...
New customers can take $200 off the purchase of any new Apple iPhone model at Xfinity Mobile through 8/17/20. Service plan required. Existing customers can purchase an iPhone and receive $200 back in... Read more
B&H now offering $100-$200 discount on Ap...
B&H Photo has new 2020 13″ 2.0GHz MacBook Pros on sale for $100-$200 off Apple’s MSRP, starting at $1649. These are the same MacBook Pros sold by Apple in their retail and online stores, and B... Read more
Apple’s 6-Core Mac mini is on sale at Amazon...
Amazon has Apple’s new 2020 6-Core Mac mini on sale for $926.25 for a limited time. Their price is $173 off Apple’s $1099 MSRP for this model and includes a $48.75 instant discount available on their... Read more
New 2020 11″ iPad Pros on sale for $50-$75 of...
Apple reseller Expercom has new 2020 11″ Apple iPad Pros on sale for $50-$75 off MSRP, with prices starting at $749. These are the same iPad Pros sold by Apple in their retail and online stores: – 11... Read more
Switch to US Cellular and get a new Apple iPh...
US Cellular has Apple’s 2020 iPhone SE on sale for $350 off for new lines of service and a US Cellular unlimited plan. Promotion comes via monthly bill credits over a 30 month period. Their deal... Read more
Apple AirPods with Wireless Charging Case on...
Amazon has Apple’s AirPods with Wireless Charging Case on sale today for only $139.98 shipped. That’s $60 off Apple’s MSRP and the lowest price we’ve ever seen for these AirPods. Sale valid for a... Read more

Jobs Board

Director, Product Management - Lead *Apple*...
…better business results. **Job Title** Director, Product Management - Lead Apple / Token Requestor Services Overview The Mastercard Digital Enablement Services Read more
*Apple* Computing Professional - Store 286 (...
**770445BR** **Job Title:** Apple Computing Professional - Store 286 (Canton) **Job Category:** Store Associates **Store Number or Department:** 000286-Canton-Store Read more
Department Manager- Tech Shop/ *Apple* Stor...
…their parents want, and our faculty needs. As a Department Manager in our Tech Shop/ Apple Store you will spend the majority of your time on the sales floor engaging Read more
*Apple* Graders/Inspectors (Seasonal/Hourly/...
Title: Apple Graders/Inspectors (Seasonal/Hourly/No Benefits) # APPLE Location: US-VA-Winchester Read more
Tier 2 Technical Support Analyst - ( *Apple*...
…Analystiless than/strong>who will analyze and determine user software needs on all Apple devices (first support contact), Windows devices, and support printers in Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.