TweetFollow Us on Twitter

Background TCL
Volume Number:9
Issue Number:12
Column Tag:TCL Workshop

A Piece of Apple Pi

Background processing with TCL

By Malcolm H. Teas, Rye, New Hampshire

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

About the author

Malcolm Teas has been programming the Macintosh for five years. He’s active with object programming in TCL and also uses C with Think and MPW. He lives, works, and consults from his house on the seacoast of New Hampshire.

I needed a project to test the new Think C version, since I have an interest in number theory, the project I picked was a Π calculation program. Most similar programs take over the machine while they’re at work. I wanted this one (just to keep life interesting) to optionally calculate Π in the background and let other applications continue. As the Mac doesn’t have preemptive multitasking, background applications only get time as permitted from the foreground application and vice versa. So, when we program time-intensive tasks, we’ve got to be nice to other software that may be running. The approach I took here is to let the user decide if this application should hog the system or not by setting an option in a menu. The default is to not hog.

To do this, I break the calculation up into a number of steps. The steps are implemented by a subclass of a TCL Chore object. This work is done at idle event time indirectly by the Dawdle() method of the bureaurocrats. The amount of CPU time that the calculation takes is the same if it’s done in the background or if the application hogs the system. However, the amount of time to the user is significantly longer if the work’s done in the background. This is due to the overhead of the time through the toolbox getting the idle event to run the calculation code. In addition, the calculation code is done in small steps and interspersed with other applications, etc. In the hog mode, it never leaves the calculation code at all but other apps don’t get CPU time.

Backgrounding is best for an application that’s got pre-calculation to do or can intersperse work with user input. As humans are so slow compared to the computer, the imbalance of speed can be put to good use this way.

Designing a chore for background processing

There are a couple of issues for chore-based background work. First, the chore has to be handled or know where to get all the information it needs for it’s processing. Second, if it’s work that gets completed that something else depends on, the chore has to be able to signal work complete. Last, chores need to be disposed of. One thing at a time.

In my case, my CPiChore class is a subclass of the CChore class. You’ll have to subclass the CChore class too as the standard class does nothing. The only method in CChore is the Perform() method (and of course those methods it inherits from CObject). My CPiChore subclass overrides the Perform() and Dispose() methods. It also has two new methods InitChore() and GetTicks() for setting the necessary data and getting information.

The InitChore() method takes all the necessary data as parameters. If I’d had a lot of data I could’ve passed a structure with the data loaded into it. However, as I only had four items, that seemed overkill for this project. Another alternative would’ve been for the chore to ask the necessary objects for the relevant data.

InitChore() takes the number of digits of Π to calculate, a pointer to the document object, and two flags to determine if the calculation should be timed and if hog mode is on. This data is stored locally. Note that the flags are stored in the object, but the document and the number of digits are stored in global variables that are defined and declared in the CPiChore.cp file. This makes them local to that file. The document object CAppPiDoc declares the CPiChore in it’s include file (CAppPiDoc.h). As a short-cut, I included the CAppPiDoc.h file in the CPiChore.cp file, and declared a global “document”. This means that I don’t have to type-cast as often when I use the “document” variable. The “Digits” variable is where the numDigits value is put. As this Π calculation code is ported, I didn’t convert all the calculation code to methods, instead, I left them and their global data in this CPiChore.cp file as straight C functions and data.

Perform() is the function in a chore that actually does the work. It’s called by the Idle() function in CApplication which is called every time an idle event happens. TCL considers an idle event to occur when we either receive a null event or a mouse-moved event. Note that if you’re doing background processing, you want null events while you’re app is in the background. To get them, the “Background null events” flag in the Size resource must be set. Use the SIZE flags popup in the Set Project Type dialog to do this.

The Idle() function also does some other things like check memory and do the Dawdle() method in the CBureaucrat object. Idle() runs through the chain of command to call all the Dawdle() methods there. It then runs through the list of chores to call Perform() on all the chores in the list.

When it gets to the Perform() method in CPiChore, CPiChore uses a stage counter to figure out what’s been done and what to do next. Basically, this determines and remembers what step it’s on. CPiChore uses the Machin algorithm to calculate Π (see the sidebar). The last step in the calculation stops the count of the time and tells the CAppPiDoc object that the chore is done by calling PiDone() in the document with the result of the calculation as it’s parameter.

The document gets the time the calculation took, sets flags for the state of the calculation and sends the result to the pane for display. The next time and idle event happens and the document’s Dawdle() method is called, the chore will be disposed of. This approach to deallocating the chore is known as lazy management of memory. It has the advantage that, as the Dawdle() method is called all the time, it’s more sure in deallocating the chore. The completion and the deallocation are in independent routines.

The pane to display this information isn’t a standard text edit pane. Text edit can only handle information up to around 30K of text characters. It’s easy to generate a value of Π that takes more space that this. I subclassed CPanorama to make a pane that just displayed a lot of text for this application. In addition, this CPiPane object also knows how to translate the digit numbers to text characters and how to display the time information too.

Implementation details

All the key user actions are handled through the DoCommand() method of the CAppPiDoc object. The one exception is the about box which is handled in the application’s DoCommand() method.

The number of digits is set in a dialog box that I use the regular TCL dialog classes to run. The DoCommand() method extracts the digit count from the dialog before it’s disposed. Although Symantec’s documentation states that the dialog objects must be subclassed to be really useful, I didn’t find the need to do that with the number of dialog view objects that know about the format and range of information. In this case, I used an integer text dialog view object that was told, via the template, what range of numbers to accept. Then, I use the FindViewByID() method to get that object and extract the now-conditioned value.

The time and hog (or “faster”) commands just toggle their values. In the UpdateMenus() method, these values are used to determine if those menu items are checked or not.

The start command is the important one. If the Π calculation chore is running, then this item is labeled “Stop”. If selected, it cancels and disposes of the chore. If the chore isn’t running, it starts it using the currently set number of digits and the timing and faster flags. It then assigns the chore to the application, this puts the chore in the chore list to be processed on an idle event. The chore will stay in the list until removed.

Once the chore is in the list, then the Perform() method is called with every idle event. If the faster or hog mode is on, then the Perform() method doesn’t return until the calculation is complete. Otherwise, it does one step and returns.

When the calculation is complete, the Perform() method calls the PiDone() method in the document which hands the result data off to the pane for display with the pane’s SetContent() method. This result data looks like the other data used in the calculation. It’s an array of character, but I use the characters as small integers. Actually, there’s a fair amount of wasted space as the integers range from 0-9. The calculation is carried out in decimal and there are custom routines to handle multiple place arithmetic.

The SetContent() method disposes any previous pointer to data (the data is held as pointers due to the ported code) and converts the data to characters for display. It does this by simply adding the integer value of the character zero to each number in the array.

When the Draw() method for the pane is called (it’s called automatically when the pane needs to be refreshed or when Refresh() is called), it sets the font and size of the text to draw. Draw() then creates a header line, draws it, skips down a little and draws the characters for Π. To do the drawing of the text, Draw() calls a routine called DrawWrapText() to wrap the text at the margins correctly.

DrawWrapText() takes parameters to the text, it’s size, and the margin, line information and whether or not to force a margin. This latter is similar to typing the return key to force a new line.

Listing:  CPiChore.cp
/*
 CPiChore
 Written and copyright by Malcolm H. Teas 1993.
 All rights reserved.
 
*/

#include "CAppPiDoc.h"

/*
 * Global variables
 */
int   Sign, 
 Zero, 
 Digits, 
 Pass,  /* two passes */
 Exp, /* exponent for divide */
 Divide;
static int constant[3]={0,25,239};

CAppPiDoc *document;
 
/*
 * These character arrays represent the digits for extended
 * precision arithmatic. (These may need to be int on 
 * some machines).
 */
#define DIGIT char
DIGIT *Power, *Term, *Result;

void copy (void);
void init(void);
void divi(register DIGIT *array);
void sub (void);
void add (void);

void CPiChore::Perform (long *maxSleep)
{
 long start;
 
 if (timeCalc)
 start = TickCount ();
 
 do  {
 switch (stage)  {
 case 0:
 init ();
 stage++;
 break;
 
 case 1:
 copy();
 Divide = Exp;
 divi(Term);
 if ( Sign > 0 ) 
 add();
 if ( Sign < 0 ) 
 sub();
 Exp = Exp + 2;
 Sign *= -1;
 Divide = constant[Pass];
 divi(Power);
 if (Pass == 2) 
 divi(Power);
 if (Zero == 0)
 stage++;
 break;
 
 case 2:
 Pass++;
 init ();
 stage++;
 break;
 
 case 3:
 copy();
 Divide = Exp;
 divi(Term);
 if ( Sign > 0 ) 
 add();
 if ( Sign < 0 ) 
 sub();
 Exp = Exp + 2;
 Sign *= -1;
 Divide = constant[Pass];
 divi(Power);
 if (Pass == 2) 
 divi(Power);
 if (Zero == 0)
 stage++;
 break;
 
 case 4:
 if (timeCalc)  {
 ticks += TickCount() - start;
 timeCalc = false;
 }
 document->PiDone (Result);
 stage++;
 break;
 
 case 5:
 break;
 }
 }  while (faster && stage != 5);
 
 if (timeCalc)
 ticks += TickCount() - start;
}

void CPiChore::InitChore (long numDigits, CDocument *doc, 
 Boolean timeIt, Boolean faster)
{
 stage = 0;
 Pass = 1;
 document = (CAppPiDoc *) doc;
 timeCalc = timeIt;
 ticks = 0;
 this->faster = faster;
 
 Digits = numDigits;
 FailNIL (Power = (char *) NewPtr (numDigits + 1));
 FailNIL (Term = (char *) NewPtr (numDigits + 1));
 FailNIL (Result = (char *) NewPtr (numDigits + 1));
}

long CPiChore::GetTicks (void)
{
 return ticks;
}

void CPiChore::Dispose (void)
{
 DisposPtr (Power);
 DisposPtr (Term);

 inherited::Dispose (); 
}

void add (void)
{
 register DIGIT *r, *t;
 register int sum, carry = 0;
    
 r = Result + Digits;
 t = Term + Digits;
 
 while( r >= Result )
 {
 sum = *r + *t + carry;
 carry = 0;
 if( sum >= 10 )
 {
 sum -= 10;
 carry++;
 }
 *r-- = sum;
 --t;
 }
}
 
void sub (void)
{
 register DIGIT *r, *t;
 register int diff, loan = 0; 
 
 r = Result + Digits;
 t = Term + Digits;
 
 while( r >= Result )
 {
 diff = *r - *t - loan;
 loan = 0;
 if( diff < 0 )
 {
 diff += 10;
 loan++;
 }
 *r-- = diff;
 --t;
 }
}
 
void divi(register DIGIT *array)
{
 register DIGIT *end;
 register int quotient, residue, digit = 0;
 
 Zero = 0;
 
 for( end = array + Digits; array <= end; )
 {
 digit    += *array;
 quotient =  digit / Divide;
 residue  =  digit % Divide;
 
 if((Zero !=0) || ((quotient+residue) != 0)) 
 Zero = 1;
 else 
 Zero = 0;
 
 *array++ = quotient;
 digit = 10 * residue;
 }
}
 
void init(void)
{
 register DIGIT *p, *t, *r, *end;
 
 p = Power;
 t = Term;
 r = Result;
 end = Power+Digits;
 
 while( p <= end )
 {
 *p++ = 0;
 *t++ = 0;
 
 if (Pass == 1) 
 *r++ = 0;
 }
 
 *Power = 16 / (Pass * Pass);
 
 if( Pass == 1 ) 
 {
 Divide = 5;
 }
 else
 {
 Divide = 239;
 }
 
 divi(Power);
 Exp = 1;
 Sign = 3 - (2 * Pass);
}
 
void copy (void)
{
 register DIGIT *t, *p, *end;
 
 t = Term;
 p = Power;
 end = Term + Digits;
 
 while (t <= end)
 {
 *t++ = *p++;
 }
}

How to calculate Π

The number Π in it’s simplest form, is the ratio of the circumference of a circle to that circle’s diameter. It’s an irrational number so it can’t be represented exactly by a ratio, or fraction, between two integers. As decimal numbering systems are essentially another way of expressing a fraction (i.e. the number 2.5 is actually the fraction 25/10), then Π, expressed as a decimal number, has an infinite number of places. A good reference for Π calculations is the book “History of Π” by Petr Beckmann.

The Π calculation algorithms work by interating over an approximation to Π. Each iteration, or time through the algorithm, the accuracy of the Π estimate increases. We say that we’re calculating Π, but we’re actually calculating an approximation to it. John Wallis, a sixteenth-century mathemetician, discovered a series of fractions, that when multiplied together result in Π. These are two ways to write Wallis’ product:

While this works fine, it’s also quite slow to converge or increase in accuracy, each fraction added doesn’t increase the accuracy very much. The Apple Π program in the article uses the Machin algorithm which converges much faster. It sums more complex fractions to speed up the process. More recently, mathemeticians using elliptical integrals discovered the holy grail of Π calculations: an algorithm, that while quite complex, doubles the number of accurate digits of Π for each iteration.

I ported the Machin algorithm from a version by Bryan Costales, who in turn ported it from a version by Robert Bishop. The algorithm is based on the equation:

[This is a Taylor expansion of 16 * Arctan(1/5) - 4 * Arctan(1/239). Tech. Ed.]

I use arrays of digits to implement the numbers and have written my own routines to do the arithmetic with these numbers. The calculation above is broken down into a number of steps. A step is done each time through the idle loop in the application.

Some have claimed that calculating Π to ever increasing numbers of digits (the record is around 40 million digits currently) is unecessary and not useful. However, when companies install a new supercomputer, this kind of calculation can be used for testing as it repeats intensive CPU work.

Number theorists use the results of long Π calculations to analyze the characteristics of the number, and through it, other similar numbers. Since number theory is a fundamental branch of mathematics that’s used in cryptography and computer theory this work may shed light on some aspects of mathematics that can be of practical use. Besides, it’s fun.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.