问题
I am using libDispatch (GCD) opensource on Android platform. So, most of the complex time consuming tasks are being done through NDK (where i am using libDispatch).
For some calls, I am using dispatch_async(get_main_queue)...This is where the problem is coming... I am able to run tasks in the concurrent queues but not on main queue. Since this requires dispatch_main() to be called which we cannot do on here as Java thread will be blocked in that case. So, is it possible to run the Java UI on some secondary thread and hook the dispatch_main() to serve the dispatch_main_queue here? OR : Do I need to keep serving the main_queue from JAva main UI thread through JNI ?
回答1:
Look into _dispatch_main_queue_callback_4CF
which is the function you can call to drain the main queue. It will return like a normal sensible function after executing the queued operations, instead of killing the thread like dispatch_main
.
Note that you'll need to call _dispatch_main_queue_callback_4CF
on a regular basis from your Java UI thread, possibly each iteration. The official Cocoa implementation uses _dispatch_queue_wakeup_main()
which uses mach messages to kick the main thread out of any sleep states so it can guarantee the callback function is called quickly, but you'd have to do some work to enable that and build your own libDispatch port. In reality on Android I don't think the main UI thread is ever put to sleep while your app is active so it shouldn't be an issue.
There is a ticket open on the libDispatch site at https://libdispatch.macosforge.org/trac/ticket/38 to make _dispatch_main_queue_callback_4CF
a public function. The ticket is marked "Accepted" but no word on if/when that will happen.
来源:https://stackoverflow.com/questions/18916567/libdispatch-serving-main-queue-without-dispatch-main-on-android