TweetFollow Us on Twitter

Threaded Apple Events

Threading Apple Events

Or: How I Learned to Stop Worrying and Love to Bomb

By Grant Neufeld, InfoDesign Corporation

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

As Jon Wiederspan points out elsewhere in this issue, threading is becoming a serious problem for webmasters intent on getting speed out of their servers. In C the problem is compounded because the AppleEvent Manager does not handle multiple simultaneous events (and Apple events are used to communicate with CGI applications). Grant Neufeld has developed a solution to this problem and distributes a CGI framework that implements it for you. In this article, he shows us how it's done.

On the Thread Manager, see also:

For Frontier as a possible solution to threading difficulties, see MacTech Magazine 12.1 (January 1966) 63-65; see also the technologies discussed by Jon in our MacWorld Expo report. On writing your CGI in C, see MacTech Magazine 11.9 (September 1995) 33-42.

The Problem of Reentrancy

As I recently discovered, trying to combine Apple events with the Thread Manager is an awkward and mind-altering experience. There are some fundamental - and obscure - requirements that are easy to miss (or so I'd like everyone to believe, so that I don't have to be so embarrassed by my own oversight).

The fundamental problem is that AEProcessAppleEvent is non-reentrant. So, if you call it, you can't call it again until the event finishes processing. I didn't know this when I originally designed the threading for my CGI framework, so I happily set about an implementation whereby I could call AEProcessAppleEvent multiple times before finishing the first call - all through the glory of the Thread Manager. My incorrect code looked like:

/* warning: bad code! Don't try this at home! */
/* Called from main event loop when a high level event arrived. */
void doHighLevelEvent ( EventRecord *theEvent )
{
 OSErr     theErr;
 ThreadID  theThread;
 
 if ( gHasThreadMgr ) {
// MyNewThreadFromPool is just a custom method to simplify
// using threads from a pool.
// Remember: this particular example of Apple event threading
// is wrong - don't do it this way!
 theErr = MyNewThreadFromPool ( doAEThread, theEvent,
 (void**)nil, &theThread );
 }
 if ( !gHasThreadMgr || (theErr != noErr) ) {
// If threading isn't available, or the attempt to thread failed,
// process the Apple event without threading.
 theErr = AEProcessAppleEvent ( theEvent );
 }
}

/* The thread entry function that was used to process the Apple event. */
pascal void * doAEThread ( void *theEvent )
{
 OSErr     theErr;
 ThreadID  currentThread;
 
 theErr = AEProcessAppleEvent ( (EventRecord *)theEvent );
 
 GetCurrentThread ( &currentThread );
 DisposeThread    ( currentThread, (void *)theErr, true );
 
 return (void *)theErr;
}

The amazing thing is that nobody - including me - caught the error until Wayne K. Walrath took a look at the code (in the eleventh release) and noticed my mistake. By then, programs were already shipping and in commercial use - including my own Random URL CGI.

So, why didn't anyone notice the code crashing? The code we all had in our threads happened to be fast enough to finish before new Apple events came in. This doesn't mean it would never crash; given a situation where two Apple events came in almost simultaneously, the code would certainly flop.

Thankfully, I had the prescience to include a suitable disclaimer and label the code "beta" and "subject to errors" to cover my legal posterior. However, my public esteem was in jeopardy! Worse still, I couldn't touch the code for a few days after receiving the bug report because of job obligations. Actually, that was a good thing because the time spent thinking about the code gave me a good basis to start from when I did actually get down to work.

Moral: Think before you code. (Carefully reading the documentation isn't a bad idea either!)

Suspending Apple Events

My original code attempted to thread every Apple event. This is not the case with the corrected code. A new thread should only be initiated within the context of an AEProcessAppleEvent call if the Apple event has been successfully suspended. Suspension of Apple events involves calls to the functions AESuspendTheCurrentEvent and AEResumeTheCurrentEvent.

If the Apple event does not suspend, you can't make any further calls to AEProcessAppleEvent, so you must not create a sub-thread unless you implement a mechanism to prevent calls to AEProcessAppleEvent until the current Apple event finishes. If you want to be creative, you can write your own Apple event dispatcher to allow reentrancy, thereby making it easier to deal with threads. People might call you crazy, but you can do it.

Which brings us to the obligatory complaint about lack of sufficient (and clear) documentation (which is part of the reason I'm writing this). Inside Macintosh: Interapplication Communication doesn't sufficiently cover the use of the necessary calls and provides no sample code for suspending Apple events (see IM:IAC 4.85-88). Hopefully, this article helps fill that gap.

The CGI Apple event is the only one I'm concerned about threading for my framework, so I didn't bother with any of the other events. I handle the Apple event arrival in the normal way with a handler installed to be called by AEProcessAppleEvent:

/* Apple event Handler for the CGI WWW sdoc event */
pascal OSErr
CGIAESearchDoc ( AppleEvent *theAppleEvent,
 AppleEvent *theReply, long Reference )
{
 OSErr     theErr;
 CGIHdl    theCGIHdl;
 ThreadID  theThread;
 
// Allocate the CGIHdl data structure - zeroing out its contents.
 theCGIHdl = (CGIHdl)
 MyNewHandleClear ( sizeof(CGIrecord), &theErr );
 if ( theCGIHdl == nil ) {
 return theErr;
 }
 
// Store references to the apple event and reply records.
 (*theCGIHdl)->appleEvent = *theAppleEvent;
 (*theCGIHdl)->replyEvent = *theReply;
 
 if ( gHasThreadMgr ) {
// It is necessary to suspend the Apple event in order to thread its processing
// because of some real weirdness with AEProcessAppleEvent not being
// "reentrant." This means you can't be processing multiple Apple events at
// the same time, so they have to be ‘suspended' if you want to deal with more
// than one (I.E., multi-threaded processing).
 theErr = AESuspendTheCurrentEvent ( theAppleEvent );
 if ( theErr == noErr) {
 (*theCGIHdl)->suspended = true;
// Apple event has been suspended, so we can spawn a thread for processing.
 theErr = MyNewThreadFromPool (
 CGIAESearchDocProcessThread, theCGIHdl,
 (void**)nil, &theThread );
 }
 }
 
 if ( !gHasThreadMgr || (theErr != noErr) ) {
// If threading isn't available, or the attempt to thread failed, or the attempt to
// suspend the Apple event failed, process the Apple event without threading.
 theErr = cgiAESearchDocProcess ( theCGIHdl );
 } else {
// We suspended the Apple event, and spawned the thread, now let's start it.
 YieldToThread ( theThread );
 }
 
 return theErr;
}

The support for threading begins in the CGIAESearchDoc function. First, I confirm the presence of the Thread Manager. If it is available, I attempt to suspend the Apple event so that it will be safe to process subsequent Apple events before finishing the current one. If the suspension is successful, I call my thread function for the event, which in turn calls the function that does the actual work of handling the event request.

/* Entry point for CGI handler thread. threadParam must not be nil. */
pascal void *
CGIAESearchDocProcessThread ( void *threadParam )
{
 OSErr     theErr;
 CGIHdl    theCGIHdl;
 ThreadID  currentThread;
 
// The threadParam is used to pass the CGIHdl.
 theCGIHdl = (CGIHdl)threadParam;
 
 theErr = cgiAESearchDocProcess ( theCGIHdl );
 
// Find the ID of current thread and use DisposeThread to dispose of it so that 
// my custom thread termination procedure will be used to recover this thread's
// allocation for the thread pool.
 GetCurrentThread ( &currentThread );
 DisposeThread ( currentThread, (void *)theErr, true );
 
// This line below is actually irrelevant, since the DisposeThread call above
// will result in the immediate termination of this thread.
// I keep it in because a return result is needed for the compiler not to issue a
// warning (and I have the "treat all warnings as errors" flag set in my
// compiler, like every programmer should).
 return (void *)theErr;
}

The basic flow of my CGI Apple event handling (if we ignore the threading) starts with CGIAESearchDoc which leads to cgiAESearchDocProcess (which calls CGIAEResumeComplete if the Apple event is suspended), finishing with cgiAEComplete. This structure allows the necessary threading and Apple event "wrapper" functions to be put around the cgiAESearchDocProcess. If the Apple event is successfully suspended, an attempt is made to create the thread, which then carries the remainder of the processing. If either the suspend or thread fails, processing will still occur - just without threading.

Resuming the Apple event

cgiAESearchDocProcess checks the suspension of the Apple event to determine how it should call the completion function. If the Apple event was suspended, it must be resumed using AEResumeTheCurrentEvent before cgiAEComplete can be called.

/* Process the CGI WWW sdoc Apple event.
    theCGIHdl must be valid (non-nil) and unlocked. */
static OSErr
cgiAESearchDocProcess ( CGIHdl theCGIHdl )
{
 OSErr       theErr;
 AppleEvent  theAppleEvent;
 
// Copy the AppleEvent record pointer into a local variable for faster access.
 theAppleEvent = (*theCGIHdl)->appleEvent;
 
// The following section (not shown in this listing) is where the parameters are
// pulled from the CGI Apple event and allocated in the CGI Handle.
// That is followed by a call to the application specific CGI handler function.
 
 if ( (*theCGIHdl)->suspended ) {
// We're in a suspended Apple event, so we'll need to resume the
// Apple event to have it complete and return the reply properly.
 theErr = AEResumeTheCurrentEvent (
 &theAppleEvent, &((*theCGIHdl)->replyEvent),
 vCGIAEResumeCompleteUPP, (long)theCGIHdl );
 } else {
// We weren't suspended, but still need to take care of the Apple event
// reply record.
 theErr = cgiAEComplete ( theCGIHdl );
 }
 
 return theErr;
}

/* Call the event completion function (cgiAEComplete) when resuming
     suspended Apple events. theReference must be a CGIHdl. */
pascal OSErr
CGIAEResumeComplete ( const AppleEvent *theAppleEvent,
 AppleEvent *theReply, long theReference )
{
 OSErr  theErr;
 
 theErr = cgiAEComplete ( (CGIHdl)theReference );
 
 return theErr;
}

/* Complete the CGI Apple event. theCGIHdl must be valid. */
static OSErr
cgiAEComplete ( CGIHdl theCGIHdl )
{
 OSErr  theErr;
    
 HLock ( (Handle)theCGIHdl );
 
 if ( (*theCGIHdl)->responseData != nil ) {
// If the user's "MyCGIProcess" function set the responseData properly, return it.
 theErr = AEPutParamPtr ( &((*theCGIHdl)->replyEvent),
 keyDirectObject, typeChar,
 (Ptr)((*theCGIHdl)->responseData),
 (*theCGIHdl)->responseSize );
 } else {
// If the user's "MyCGIProcess" failed to set the responseData properly,
// return an error header.
 theErr = AEPutParamPtr ( &((*theCGIHdl)->replyEvent),
 keyDirectObject, typeChar, (Ptr)gHTTPHeaderErr,
 gHTTPHeaderErrSize );
 }
 
 HUnlock ( (Handle)theCGIHdl );
    
 cgiDisposeHandle ( theCGIHdl );
 
 return theErr;
}

Using Preallocated Threads

One thing to be concerned about is overloading on threads. Having a handful of threads available can improve performance, but running dozens of threads can bog things down - especially in terms of memory usage, since each thread has its own stack allocated in the application heap. Because of this, creating threads can quickly eat up a significant chunk of memory. You can reduce this somewhat by calculating the maximum total space you will need for the thread stack and using that value in place of the default when allocating threads. However, memory use by threads will still be a significant matter.

A good strategy is to preallocate a limited number of threads and use only those. This has the double advantage of increasing the thread allocation speed and reducing heap fragmentation. In your application initialization sequence, you'll need to allocate a pool of threads after confirming that the Thread Manager is available.

// Pre-allocate the required number of threads.
// kStartupThreadsPreallocate is a constant defined in "MyConfiguration.h"
// which I use to define the total number of threads to preallocate
 CreateThreadPool ( kCooperativeThread,
 kStartupThreadsPreallocate, nil );

You will want to use a wrapper call to NewThread to put the current thread to sleep if there aren't any available threads in the pool. This is done so that one of the active threads may have time to complete, at which point the finishing thread will "wake up" the sleeping thread, allowing it to continue on from the point where it went to sleep, with a thread (the one that just finished) now available from the preallocated pool.

/* Allocate a new thread from the existing pool of threads.
    If there are no threads available, yield to other threads until one finishes.
    The Thread Manager must be available for this function to work. */
OSErr
MyNewThreadFromPool ( ThreadEntryProcPtr threadEntry,
 void * threadParam, void ** threadResult,
 ThreadID * threadMade )
{
 OSErr     theErr;
 short     threadsFree;
 ThreadID  currentThread;
 
 theErr = GetFreeThreadCount ( kCooperativeThread,
 &threadsFree );
 if ( theErr == noErr ) {
 theErr = GetCurrentThread ( &currentThread );
 }
 if ( (theErr == noErr) && (threadsFree == nil) ) {
// Put the current thread to sleep, to be woken up when a thread becomes available.
 gThreadSleeper = currentThread;
 theErr = SetThreadState ( currentThread,
 kStoppedThreadState, nil );
 }
 if ( theErr == noErr ) {
// Install the new thread using a premade thread from the pool.
 theErr = NewThread ( kCooperativeThread,
 threadEntry, threadParam, nil,
 kFPUNotNeeded + kUsePremadeThread,
 threadResult, threadMade );
 }
 if ( theErr == noErr ) {
// Set the termination function for the thread.
 SetThreadTerminator ( *threadMade,
 myThreadTermination, nil );
 
// Increment the total number of sub-threads.
 ++gThreadTotal;
 
// Decrease the sleep ticks so we'll take more processing time.
 gSleepTicks = kSleepTicksWhenBusy;
 }
 
 return theErr;
}

A thread termination callback procedure is used to wake up the sleeping thread when another thread is finished.

/* The Thread Manager must be available for this function to work. */
pascal void
myThreadTermination ( ThreadID threadTerminated, void
 *terminationProcParam )
{
 if ( gThreadSleeper != nil ) {
// Wake up the sleeping thread so that it may be called when other threads yield.
 theErr = SetThreadState ( gThreadSleeper,
 kReadyThreadState, nil );
 gThreadSleeper = nil;
 }
 
// Lower the count of sub-threads.
 --gThreadTotal;
 
 if ( gThreadTotal == nil ) {
// If there are no more threads, reset the sleep ticks to normal.
 gSleepTicks = kSleepTicks;
 }
}

When to Thread

After considering all this, you should ask yourself whether you really need to thread your Apple event handlers. The keys to answering this question are whether there are any points in the handler where it would be appropriate to yield the processing to other threads, and, more importantly, whether the handler is big and slow enough to see performance benefits from threading. Keep in mind that there is overhead and complexity added when you use cooperative threading.

As an example, I didn't thread my Random URL CGI because its response time (with rare exception) is under a second. To thread it would only add time to the total process without any real improvement in performance (not to mention increased memory requirements). On the other hand, a form-handling CGI I'm working on is threaded, because it will frequently have to talk (through Apple events) to other applications, which can slow things down appreciably (and waiting for a response is a great time to yield processing).

Further Considerations

If your application spawns threads from any threads apart from the main thread, you will need to maintain a queue of sleeping threads rather than just the one stored in this article's code. Another important consideration, that hasn't been covered here, is to make sure that WaitNextEvent is still periodically called if the main thread is put to sleep. You don't absolutely have to do that, but it is strongly recommended so that other applications and processes can have time to run. You may want to think about resetting the calling application's Apple event timeout timer when an event is taking a long time to process. Additionally, any CGI that wants to support the new "Send Partial" multi-stage reply mechanism in WebSTAR will need to make more advanced use of threading and Apple events.

Grant's CGI framework comes with project files for the CodeWarrior, THINK C and Symantec Project Manager environments.

Discussion mailing list: grantcgi@arpp.carleton.ca with the subject set to: help

Home page: http://arpp.carleton.ca/cgi/framework/

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.