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
  • 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.
    COCOA
    • 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"
    
    #import 
    #include 
    
    @interface PotalNetThreadChanger : NSObject {
    @private
        CPortalNetThreadChanger* changer;
    }
    - (void)toMainThreadByChanger:(CPortalNetThreadChanger*) pChanger withIntValue:(int) intValue;
    + (PotalNetThreadChanger*)default;
    @end
    
    
    @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
    {
        pChanger->onMainThread(intValue);
    }
    
    - (void)onMainThreadWithId:(NSString*)stringValue;
    {
        int intValue = [stringValue intValue];
        [self onMainThreadToChanger:changer withIntValue:intValue];    
    }
    
    - (void)toMainThreadByChanger:(CPortalNetThreadChanger*) pChanger withIntValue:(int) intValue
    {    
        if (![NSThread isMainThread])
        {
            @synchronized(self){
                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];
            }
            return;
        }
        [self onMainThreadToChanger:pChanger withIntValue:intValue];
    }
    
    + (PotalNetThreadChanger*)default
    {
        static PotalNetThreadChanger* defaultChanger = [[PotalNetThreadChanger alloc]init];
        return defaultChanger;
    }
    @end
    
    CPortalNetThreadChanger::CPortalNetThreadChanger()
    {
        
    }
    CPortalNetThreadChanger::~CPortalNetThreadChanger()
    {
        std::clog << "class CPortalNetThreadChanger destructed successfully" << std::endl;
        [[PotalNetThreadChanger default]release];
    }
    void CPortalNetThreadChanger::toMainThread(int value)
    {
        [[PotalNetThreadChanger default]toMainThreadByChanger:this withIntValue: value];
    }
    
    

    12 comments:

    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

      ReplyDelete
    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

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


      Feel free to surf to my homepage; Pure GCE

      ReplyDelete
    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

      ReplyDelete
    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

      ReplyDelete
    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

      ReplyDelete
    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

      ReplyDelete
    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

      ReplyDelete
    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 ... http://musclemaximizernow.com

      ReplyDelete
    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

      ReplyDelete
    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 [www.golfamelkis.com] 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.

      ReplyDelete