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

Together 3.6.1 - Store and organize all...
Together helps you organize your Mac, giving you the ability to store, edit and preview your files in a single clean, uncluttered interface. Features Smart storage. With simple drag-and-drop... Read more
Cloud 4.1.1 - 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
OmniFocus 2.7.1 - GTD task manager with...
OmniFocus helps you manage your tasks the way that you want, freeing you to focus your attention on the things that matter to you most. Capturing tasks and ideas is always a keyboard shortcut away in... Read more
CleanApp 5.1.1 - Application deinstaller...
CleanApp is an application deinstaller and archiver.... Your hard drive gets fuller day by day, but do you know why? CleanApp 5 provides you with insights how to reclaim disk space. There are... Read more
ForkLift 3.0 Beta 2 - Powerful file mana...
ForkLift is a powerful file manager and ferociously fast FTP client clothed in a clean and versatile UI that offers the combination of absolute simplicity and raw power expected from a well-executed... Read more
Sublime Text 3126 - Sophisticated text e...
Sublime Text is a sophisticated text editor for code, markup, and prose. You'll love the slick user interface, extraordinary features, and amazing performance. Features Goto Anything. Use Goto... Read more
1Password 6.3.3 - Powerful password mana...
1Password is a password manager that uniquely brings you both security and convenience. It is the only program that provides anti-phishing protection and goes beyond password management by adding Web... Read more
WhatsApp 0.2.1880 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
NeoFinder 6.9.3 - Catalog your external...
NeoFinder (formerly CDFinder) rapidly organizes your data, either on external or internal disks, or any other volumes. It catalogs all your data, so you stay in control of your data archive or disk... Read more
Amadeus Pro 2.3.1 - Multitrack sound rec...
Amadeus Pro lets you use your Mac computer for any audio-related task, such as live audio recording, digitizing tapes and records, converting between a variety of sound formats, etc. Thanks to its... Read more

Our 5 Favorite iMessage Sticker Packs
At long last, iMessage joins the ranks of messaging apps the likes of LINE and Whatsapp, adding an impressive collection of stickers. They’re a great way to add a little something extra to your daily conversations. [Read more] | Read more »
How to get past Vulture Island's tr...
Vulture Island is a colorful and quirky mish-mash of platforming and puzzles. It’s creative and fresh, but sometimes the game can throw a curveball at you, leaving you stuck as to how you should progress. These tips will help you explore smoothly... | Read more »
The new Clash of Kings is just for Weste...
If you’ve played the original Clash of Kings, you’ll probably recognise the city building, alliance forging and strategic battles in Clash of Kings: The West. What sets this version apart is that it’s tailor made for a Western audience and the... | Read more »
Frost - Survival card game (Games)
Frost - Survival card game 1.12.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.12.1 (iTunes) Description: *Warning: the game will work on iPhone 5C and above and iPad Pro / 4. Other devices are not supported* | Read more »
How to build and care for your team in D...
Before you hit the trail and become a dog sledding legend, there’s actually a fair bit of prep work to be done. In Dog Sled Saga, you’re not only racing, you’re also building and caring for a team of furry friends. There’s a lot to consider—... | Read more »
How to win every race in Dog Sled Saga
If I had to guess, I’d say Dog Sled Saga is the most adorable racing game on the App Store right now. It’s a dog sled racing sim full of adorable, loyal puppies. Just look at those fluffy little tails wagging. Behind that cute, pixelated facade is... | Read more »
Let the war games commence in Gunship Ba...
Buzz Lightyear famously said, “This isn’t flying, this is falling – with style!” In the case of Gunship Battle: Second War, though, this really is flying - with style! The flight simulator app from Joycity puts you in control of 20 faithfully... | Read more »
How to get a high score in Fired Up
Fired Up is Noodlecake Games’ high score chasing, firefighting adventure. You take control of a wayward firefighter who propels himself up the side of a highrise with blasts of water. Sound silly? It is. It’s also pretty difficult. You can’t... | Read more »
NBA 2K17 (Games)
NBA 2K17 1.0 Device: iOS iPhone Category: Games Price: $7.99, Version: 1.0 (iTunes) Description: Following the record-breaking launch of NBA 2K16, the NBA 2K franchise continues to stake its claim as the most authentic sports video... | Read more »
Dog Sled Saga (Games)
Dog Sled Saga 1.0.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.1 (iTunes) Description: A game by Dan + Lisa As a rookie musher, foster a dogsledding team whose skills will grow if they're treated right. Week by... | Read more »

Price Scanner via

Toughbook Celebrates 20 Years of Ruggedized M...
Panasonic System Communications Company of North America, Division of Panasonic Corporation of North America (Panasonic) today celebrates the 20th anniversary of its industry-leading Toughbook mobile... Read more
12-inch 1.1GHz Gray Retina MacBook on sale fo...
B&H Photo has the 2016 12″ 1.1GHz Gray Retina MacBook on sale for $1199.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
13-inch 2.5GHz MacBook Pro (Apple refurbished...
Apple has Certified Refurbished 13″ 2.5GHz MacBook Pros available for $829, or $270 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free: - 13″ 2.5GHz MacBook Pros... Read more
Save 30% on Camera Guard’s Secure Protection...
To celebrate the release of macOS Sierra, Miami-based security solutions company, ProtectStar has announced a special 30% discount on Camera Guard Professional for Mac 2016. This innovative security... Read more
DVDFab Special Deal – Get a 1-Year Free Licen...
Beijing, China based specialist in the field of DVD, Blu-ray and video backup solutions, Fengtao Software has launched its Autumn Special Deals 2016, giving a 1-year free license of a randomly picked... Read more
21-inch iMacs on sale for up to $120 off MSRP
B&H Photo has 21″ iMacs on sale for up to $120 off MSRP including free shipping plus NY sales tax only: - 21″ 3.1GHz iMac 4K: $1379 $120 off MSRP - 21″ 2.8GHz iMac: $1199.99 $100 off MSRP - 21″ 1... Read more
13-inch 2.7GHz/256GB Retina MacBook Pro on sa... has the 13″ 2.7GHz/256GB Retina Apple MacBook Pro on sale for $151 off MSRP including free shipping: - 13″ 2.7GHz/256GB Retina MacBook Pro (sku MF840LL/A): $1348 $151 off MSRP Read more
Apple TVs on sale for up to $50 off MSRP
Best Buy has 32GB and 64GB Apple TVs on sale for $40-$50 off MSRP on their online store. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store... Read more
Apple refurbished 13-inch Retina MacBook Pros...
Apple has Certified Refurbished 13″ Retina MacBook Pros available for up to $270 off the cost of new models. An Apple one-year warranty is included with each model, and shipping is free: - 13″ 2.7GHz... Read more
Duplicate Sweeper Free On Mac App Store For O...
To celebrate the launch of Apple’s latest macOS Sierra, Stafford, United Kingdom based Wide Angle Software has announced that its duplicate file finder software, Duplicate Sweeper, is now available... Read more

Jobs Board

Sr. *Apple* Mac Engineer - Net2Source Inc....
…staffing, training and technology. We have following position open with our client. Sr. Apple Mac Engineer6+ Months CTH Start date : 19th Sept Travelling Job If Read more
*Apple* Retail - Multiple Positions-Norfolk,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Lead *Apple* Solutions Consultant - Apple (...
# Lead Apple Solutions Consultant Job Number: 51829230 Detroit, Michigan, United States Posted: Sep. 19, 2016 Weekly Hours: 40.00 **Job Summary** The Lead ASC is an Read more
US- *Apple* Store Leader Program - Apple (Un...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.