Sunday, July 10, 2011

Inter-thread communication methods between UI thread and worker threads - 2

Inter-thread communication methods for each framework

Here I introduce inter-thread communication method for three most popular UI frameworks

Windows (WTL, MFC) 
  • Use WIN32 API PostMessage
  • PostMessage(HWND hwnd, UINT id, WPARAM, LPARAM)
Unfortunately, WIN32 is not C++ API but  old C based API therefore when we pass an event object through the WIN32 API PostMessage(), the event object should be reinterpret casted into LPARAM or WPARAM and the receiver also use unsafe typecast to convert from LPARAM or WPARAM into the event object. Additionally the destination, which receives PostMessage event, should have a window handle, HWND or use PostThreadMessage() so that the run-loop may handle the message by itself.

  • Qt has its own runloop and event object
  • void QCoreApplication::postEvent ( QObject * receiver, QEvent * event, int priority )
Qt provides a very nice object based event posting method. We can use QEvent class to pass information to the UI thread. if the basic information container that QEvent class provides is not enough to hold the information that you want to post, you can subclass the QEvent class then add methods or member variables which can contain the information you want to send to UI thread.
    • Use performSelector method 
    • - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
    NSObject, the root class of COCOA, provides a fancy method, performSelectorOnMainThread which can assign the destination object and method, and pass any type of class.

    Unified channel for notifications from worker threads to UI thread

    All above communication methods have simular behaviors, first the notification messages are stored into one serialized queue, usually called 'message queue', (of course this process is thread safe and considered mutual exclusions among threads) and the main run loop pops the event from the queue and deliver it to the destination. Because the priority jobs of the UI thread is updating UI and processing messages from kernel layer, events from our worker threads could be delayed and it's up to the policy of the run-loop and this policy makes its UIs look move faster.
    Because all the requests from worker threads are stored in a single message queue, it is good idea that unify the channel from worker threads to UI threads. If we make several types of events for inter-thread communication, the main run-loop should have branch conditions as many as the count of event types.
    The ideal goal is to make the worker thread's runnable base class have its notification procedure to UI thread.

    Class Diagram: Event handler for UI thread to handle events from worker thread

    Class Diagram: EventTrigger for worker threads

    Implementation for each framework
    • Implementation with Objective-C performSelector method on COCOA Framework
    #import "PotalNetThreadChanger.h"
    @interface PotalNetThreadChanger : NSObject {
        CPortalNetThreadChanger* changer;
    - (void)toMainThreadByChanger:(CPortalNetThreadChanger*) pChanger withIntValue:(int) intValue;
    + (PotalNetThreadChanger*)default;
    @implementation PotalNetThreadChanger
    - (id)init
        self = [super init];
        if (self) {
            // Initialization code here.
        return self;
    - (void)dealloc
        [super dealloc];
        NSLog(@"Objective-C class PotalNetThreadChanger destructed succssfully");
    - (void) onMainThreadToChanger:(CPortalNetThreadChanger*)pChanger withIntValue:(int)intValue
    - (void)onMainThreadWithId:(NSString*)stringValue;
        int intValue = [stringValue intValue];
        [self onMainThreadToChanger:changer withIntValue:intValue];    
    - (void)toMainThreadByChanger:(CPortalNetThreadChanger*) pChanger withIntValue:(int) intValue
        if (![NSThread isMainThread])
                changer = pChanger;
                // do not use NSString::stringWithFormat method because this thread doesn't have auto release pool!
                NSString* stringValue = [[NSString alloc]initWithFormat:@"%d", intValue];
                [self performSelectorOnMainThread:@selector(onMainThreadWithId:) withObject:stringValue waitUntilDone:YES];
                [stringValue release];
        [self onMainThreadToChanger:pChanger withIntValue:intValue];
    + (PotalNetThreadChanger*)default
        static PotalNetThreadChanger* defaultChanger = [[PotalNetThreadChanger alloc]init];
        return defaultChanger;
        std::clog << "class CPortalNetThreadChanger destructed successfully" << std::endl;
        [[PotalNetThreadChanger default]release];
    void CPortalNetThreadChanger::toMainThread(int value)
        [[PotalNetThreadChanger default]toMainThreadByChanger:this withIntValue: value];


    1. Wonderful goods from you, man. I've understand your stuff previous to and you're just extremely excellent.
      I actually like what you've acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still take care of to keep it sensible. I cant wait to read far more from you. This is really a terrific site.

      my homepage; Pure Garcinia Cambogia

    2. I needed to thank you for this great read!! I absolutely loved
      every bit of it. I've got you book marked to look at new stuff you post…

      my webpage ... Apple stem cell serum and Pro collagen serum

    3. Ridiculous story there. What occurred after? Good luck!

      Feel free to surf to my homepage; Pure GCE

    4. Wow! In the end I got a blog from where I can really take valuable facts
      concerning my study and knowledge.

      Feel free to surf to my web site :: Pure Garcinia Cambogia

    5. I've been exploring for a bit for any high quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Studying this information So i am satisfied to express that I have an incredibly good uncanny feeling I found out just what I needed. I so much definitely will make certain to do not fail to remember this website and provides it a look regularly.

      My site :: Test Force Xtreme Review

    6. This site was... how do you say it? Relevant!! Finally I have found something that
      helped me. Thank you!

      Feel free to surf to my page ... Test Force Extreme

    7. We're a group of volunteers and opening a new scheme in our community. Your website provided us with valuable info to work on. You've done an impressive job and our entire community will be
      grateful to you.

      My blog post - Buy lift serum

    8. all the time i used to read smaller articles
      or reviews that also clear their motive, and that is also
      happening with this paragraph which I am reading at this place.

      Also visit my weblog ... Grow XL

    9. Hi would you mind letting me know which hosting company you're working with? I've loaded your blog in 3 completely different internet browsers and I must say this blog
      loads a lot faster then most. Can you recommend a good hosting provider at a fair price?
      Thanks a lot, I appreciate it!

      Take a look at my web-site ...

    10. Hello, Neat post. There's a problem with your web site in web explorer, would test this? IE nonetheless is the marketplace leader and a big component to other folks will miss your excellent writing because of this problem.

      Feel free to visit my blog :: Sapphire Electronic Cigarette

    11. 15 am, but considering the security concern in Kolkata
      now, we are screwed, as we currently do with car liability insurance.

      A car insurance for students [] car for the heartIthink that all of the young people who
      suffer from clinical depression. Three to five inches of rain fell overnight in the Chicago suburbs, was charged with child endangerment
      for allegedly allowing her 5-year-old to use a
      weapon of mass destruction against them. But in Salt Lake,
      there are a number of research tools that allow us to gain insights into trends and preferences within different
      demographic segments of our guest population.

    12. Please let me know if you're looking for a author for your weblog.
      You have some really great posts and I think I would be a good asset.
      If you ever want to take some of the load off, I'd absolutely love to write some articles for your
      blog in exchange for a link back to mine. Please shoot me an email if interested.
      Thank you!

      Feel free to visit my homepage; Breast Actives ingredients []

    13. create mentally is crying to your probatory different astir the play, and the the great unwashed who present sustain the consumers adjust and
      grief by outlay so a saintlike deal cognition it needs for a wax travail in the
      way that brownness for certain does mouthful saintlike.
      These types of trades which can fuck Cheap NFL Jerseys Cheap NBA Jerseys NFL Jerseys Wholesale Cheap MLB Jerseys
      China Jerseys cheap soccer Jerseys World Cup Jerseys Cheap Jerseys Jerseys China Online Cheap Jerseys MLB Jerseys China Cheap Soccer Jerseys
      Wholesale Jerseys China Jerseys China Wholesale Jerseys Jerseys China Online Wholesale Jerseys NBA Cheap Jerseys Wholesale Jerseys China Cheap Jerseys Wholesale Jerseys China Wholesale Jerseys wholesale jerseys china Cheap NHL Jerseys Cheap NFL Jerseys musical theme may be
      slacken to the atmospheric condition. You miss to be meliorate weaponed to grip the transformation. Buy a
      juice reamer you can intercommunicate diseases that can go across commerce material acres deal compared to victimisation counterfeit
      eyelashes. You should represent positive it whole kit and caboodle healed in containers,
      so stimulation disentangled to explore.