YOUR FEEDBACK
IBM Buys Its Way Out of Antitrust Trouble
Plato wrote: L.L.Bean was never actually a customer of PSI. At most, they we...


2007 West
GOLD SPONSORS:
Active Endpoints
Your SOA Needs BPEL for Orchestration
BEA
Virtualized SOA: Adaptive Infrastructure for Demanding Applications
Nexaweb
Overcoming Bandwidth Challenges with Nexaweb
TIBCO
What is Service Virtualization?
SILVER SPONSORS:
WSO2
Using Web Services Technologies and FOSS Solutions
Click For 2007 East
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
MXDJ TOP LINKS YOU MUST CLICK ON !


Get the most out of each of your CPU's ticks!
Multithread programming in Macromedia Director Xtras

Digg This!

Page 2 of 4   « previous page   next page »

For a real-world example, imagine that you place an order at your local electronic store for the latest super-cool MP3 player, but the product is currently out-of-stock. The sales associate however promises they will receive it within the next 10 days. One possible -- but inefficient -- way for you to get your hands on the product is to call the store every hour or so to find out whether or not it has arrived. This would waste a lot of time for both you and the store and is what you would define as a polling mechanism.

Another and better mechanism would be for the sales associate to phone you once they receive the product. This is a notification mechanism and as you can see, is far more efficient. We will take this mechanism and adapt it to our game board example.

Imagine the following context: It is the computer's turn to compute the next move. Your Lingo code calls your multithreaded Xtra, which creates a new thread (the "secondary thread"), which calls the game engine with the appropriate parameters, and returns control to Director and your Lingo code in the main calling thread. While the game engine is computing its best next move in the secondary thread, you are free to make your Lingo code do whatever you feel is appropriate, for example you could display an animation, respond to user interactions, etc. Your Lingo code wouldn't need to be different than any other ordinary Lingo code and thus can be architected exactly the way you want it. Director and your Lingo code would obviously run in the main thread.

When the game engine completes its computation, it and returns to your multithreaded Xtra, the Xtra would then call a handler in Director which you would have designated to take over after the next move's result is delivered. The game Xtra engine would do this in the secondary thread as it would not have access to the main thread at this point.

Unfortunately, this approach would inevitably lead to a crash in Director. This is because Director is not protected against reentrancy: you cannot call a Director method from anywhere else other than the main thread. You would have to find a way to catch its main thread first.

To illustrate this mechanism with our real-world example, having the secondary thread directly call the completion handler in your Director movie would be equivalent to the sales associate calling to notify you that your MP3 player has arrived, and expecting you to take delivery right away even though you may be in the shower at that time of the call and not in a position to instantaneously respond to his or her call.

Subtle Multithreading: the Producer/Consumer Model
Let's improve the notification mechanism introduced above. Let's have the sales associate call and leave a voicemail informing you that your MP3 Player has arrived. This would allow you to retrieve and respond to the voicemail in the order that best suits your schedule.

To do the above in a software program, you would need to implement a Producer/Consumer communication model. The main thread (Director) would be the Consumer. The secondary thread would be the Producer. There would be a FIFO (First-In First-Out) message queue to coordinate their efforts. The message queue works exactly like the answering machine in our real-world example between the sales associate (the Producer) and you (the Consumer). When the Producer has something to signal to the Consumer, it adds it to the message queue. Every time the Consumer has spare time, it checks the queue to see if something is waiting for it. When it finds a message, it retrieves it and processes it.

In our board game example, this translates to the following sequence: When it's the computer's turn to make a move, your Lingo calls the Xtra which immediately returns control to your Lingo. While your Lingo code is free to interact with the user, the Xtra spawns a secondary thread and sends it to the game engine for processing. When the game engine is ready with its next move, it posts the result to the message queue using the secondary thread (the only thread it has access to). communicates it to the Xtra in the secondary thread. The Xtra posts a message to the main thread in the message queue. The main thread then picks up the message and processes it.

While this mechanism is only explained in the context of the completion of a computation, it equally applies to the retrieval of the progress of a task or its error condition.

Making it Bullet-Proof
To make sure your threads work harmoniously together, you have to make sure the following conditions are met.

  • Memory Sharing: The queue is a memory zone shared by multiple threads. You must make sure that the threads don't modify the queue at the same time. Luckily, operating systems implement the concept of Critical Section to protect you against this problem. A Critical Section is a portion of the program that is executed continuously by a thread without being interrupted by any other thread. Thus, to make sure that one thread is not retrieving a message from the queue and reorganizing memory while the other thread is still posting the same message - and probably reorganizing memory too -, you must include each message addition and retrieval call in a Critical Section.

  • Controlling Queue Size: If the Producer adds messages to the queue faster than the Consumer can process them, your queue will indefinitely grow. That would lead to uncontrolled memory consumption, excessive memory reallocations, excessive virtual memory use resulting in excessive stress on hard disk usage and CPU. The immediate symptom would be the extreme slow down of your computer with a complete crash not too far away. If you suspect that such a problem may arise in your specific application, you should consider implementing another multithreading mechanism called Semaphore. A Semaphore is a way for multiple threads to share a limited number of resources. In this case, the resource is the memory used by the message queue and a Semaphore can be used to limit the number of items contained in it.

  • Avoiding Deadlocks: A deadlock occurs when two threads wait for each other and make it impossible for each other to resume activity. Deadlocks are often caused by a misuse of Semaphores and Critical Sections. For example, if the queue is full and the Producer tries to add a message, it first enters a Critical Section to acquire exclusive access to the queue. Then it checks the Semaphore to make sure it can indeed add a message. Since the queue is full, the Producer exits without adding the message, hoping to be able to do so in a later iteration, after the Consumer has removed one or more messages from the queue. A fraction of a second later, the Consumer tries to retrieve a message from the queue: It first tries to acquire exclusive access to the queue through a Critical Section but fails because the Producer already has acquired exclusivity through its own Critical Section. Consequently, the Consumer is unable to remove a message from the queue. This obviously creates a deadlock between Producer and Consumer.

    A Sample Implementation
    This section introduces a sample implementation of a multithreaded Xtra through a simplified model. In this Xtra, the Producer is a simple thread that counts from 1 to 1,000, and pushes the value of the counter into the message queue. The Consumer retrieves the value and calls a method in Lingo and displays it in Director.

    We only show the Windows version of this Xtra here, but the Mac OS version would be almost identical. Also, for the sake of clarity, the error checking code has been stripped out so that the essential part of the code is more apparent.

    Let's first look at the queue manager. This manager is responsible for adding (pushing) and retrieving (popping) messages. We use STL (C++'s Standard Template Library) to represent the queue. The elements in this queue are objects of type CEvent, which is a virtual class and therefore can contain any type of structure.


  • Page 2 of 4   « previous page   next page »

    About Laurent Brigaut
    Laurent Brigaut - Director of Operations, Integration New Media (INM) Laurent has been the Director of Operations at Integration New Media (INM) for 5 years. During this time, he has developed and worked on several custom Xtras for clients and was the brainchild behind INM's SecureNet Xtra and Moka Xtra, two of INM's more specialized commercial Xtras. Laurent has an engineering degree in Computer Science from the Université de Technologie de Compiègne in France (equivalent to a Masters Degree) as well as twelve years experience in software R&D. Among the organizations he has worked for are CERN (European fundamental particles research center), FIRST (integrator and trainers of software for the disabled) and INM. Laurent is an expert in object based methods and technologies.

    Sunil Gupta wrote: Excellent article. This can be used to communicate with any previously written code in C/C++. Exactly what I was interested in. Great Job!!!
    read & respond »
    LATEST FLEX STORIES & POSTS
    Adobe's Kevin Lynch and Microsoft's Scott Guthrie to Keynote AJAX World RIA Conference & Expo
    Two of the biggest launches in Rich Internet Application history took place in 2007/2008 when Adobe launched AIR 1.0 in February '08 and Microsoft launched Silverlight (September '07). At the 6th International AJAXWorld RIA Conference & Expo in October SYS-CON Events is delighted to be
    Google and Yahoo Can X-Ray Your SWF Now
    Adobe announced a collaboration with search industry leaders to dramatically improve search results of dynamic Web content and rich Internet applications.
    DreamFace Interactive Delivers Mashup Kit: DreamFace-Fx for Adobe Flex
    Following the private Beta release last month, DreamFace Interactive announced the general availability of the DreamFace-Fx Mashup Kit for Adobe Flex. As promised, DreamFace-Fx is the first Mashup Kit to reach developers in a comprehensive roadmap which will extend the DreamFace Open S
    Integration between Flex and AJAX made easy
    Flex is a great way to introduce rich Internet applications in your enterprise. But in the real world, you often have to do it gradually. Majority of the business units of any enterprise who are sold on RIA would prefer adding Flex-based components to their old but working Web 1.0 app
    AJAX and Enterprise RIA Tools - JSF, Flex, and JavaFX
    2008 is going to be an important year for Rich Internet Applications. Most organizations are delivering or planning to deliver Rich Internet Applications; however, at the same time, most IT managers are facing a dilemma: which Rich Internet Application technology and platform to use? T
    Adobe Releases Significantly Enhanced LiveCycle ES
    Adobe has released a substantially enhanced BPM/RIA solution. While LiveCycle suite isn't new software, its popularity increased in June of 2007 when the entire suite started to run on the same J2EE server and the RIA components were introduced. Today, over 5,000 enterprises use LiveCy
    SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
    SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

    SYS-CON FEATURED WHITEPAPERS

    ADS BY GOOGLE