简体   繁体   中英

PostThreadMessage equivalent on Mac OS X

I am porting an application to Mac OS X.

I need to do following task on Mac OS X too. A thread A needs to post a message to message queue of another thread B. These message involves some custom messages too. On a particular message like EXIT_LOOP, thread B comes out of message loop.

I have started message loop for thread B using CFRunLoop.

Now I cannot find how thread A can post a message to thread B.

In Windows, this is possible PostThreadMessage. There may not be straight port to Mac OS X for this, but there must be a way to do it on Mac OS X.

Please note that thread B does not know about thread A, but thread A knows thread B.

Windows Code:

MessageLoop () {
    MSG message;
    BOOL ret;
    while(ret = GetMessage(&message, NULL, 0, 0) != 0) {
        if(ret == -1)
            break;

         if(UseMessage(message) = EXIT)
             break;

    }

}

int UseMessage (MSG Message)
{
   switch(Message) {

   //Process various messages.

   case I_AM_COMPLETE:
       return EXIT;

   }
}


//Thread A:
MessageLoop ();
//Cleanup

//Thread B:
PostThreadMessage(threadidofA, I_AM_COMPLETE, 0, 0);

I believe this code may give more clarity. I want equivalent functionality on Mac OS X.

As a general bit of advice, you should take a different tack for your porting effort. Don't try to "transliterate" Win32 coding strategies to Mac ones. Revamp your design for Mac coding techniques from the ground up.

Anyway, there are various ways to achieve something similar. Probably the simplest requires that thread B use NSRunLoop rather than CFRunLoop . Then, thread A can use -[NSObject performSelector:onThread:withObject:waitUntilDone:] to run a method on thread B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM