2

I have a worker thread (pthread) to process some things on background, then I want to display the result on the screen. So I must execute some code on the UI thread or main thread.

In iOS I can use dispatch_async(dispatch_get_main_queue(), ^{ /* My code */ });, in Android I can use View.queueEvent(). Anybody can show me how to the same thing with BB 10 native SDK?

Thanks,

Solution updated.

I finally figured out the 2 methods, the first is simple, but it didn't work, I don't know why. I put it here if anyone wants to look at.

Method 1.

Use bps_channel_exec to execute some code on the thread that owns the channel. On the UI thread, create a channel, then set it active. And on the worker thread, get the active channel by calling bps_channel_get_active, then use bps_channel_exec. but it didn't work for me, continue to find the reason.

Method 2.

This method is more complicated, but simple in idea. On the worker thread, push an event to the UI thread. On the UI thread main loop, add an event handler to process the kind of event.

On worker thread: register a domain by calling bps_register_domain, then use the domain to create an event by calling bps_event_create. Next, push the event to the active channel on the UI thread by calling bps_channel_push_event.

On UI thread main loop:

for (;;) {
   bps_event_t *event = NULL;
   bps_get_event(&event, -1);

   if (event) {
      if (bps_event_get_domain(event) == the_domain_that_is_mentioned_above) {
         // Handle the event
      }
   }

   ...
}

There is a good sample here.

TienDC
  • 301
  • 2
  • 9

1 Answers1

3

You should use signals and slots. Event sent to an object are executed in their event loop, ergo signals sent to UI objects are queued and executed in the UI thread.

Also, you should consider using Qt's thread API, (see also that one) that would make integration with the rest of your app easier.

In my experience, if your worker thread mostly need one-way (thread -> rest of the app) communication, use QtConcurrent::run, if the worker is an complex object, consider starting a thread (that would create and start an event loop for signals/slots), then instantiate your objects and push them to the worker thread. Then signals sent to them will be queued and executed in the new thread.

I don't remember where I saw that advice, but if you are specifying the last argument in the connect statements, you usually do something wrong, at least I did. The default behaviour does really cover 99.9% of the cases. If the signals block the UI thread, then something in object-hierarchy/thread affinity is wrong. And it's very easy to get it wrong.

If you made your UI in QML, see C++ SIGNAL to QML SLOT in Qt

Community
  • 1
  • 1
Jean
  • 329
  • 1
  • 7