Multi-Threading in MobileInsight¶
You can use threads in MobileInsight, mainly through the python
threading
library, which is a nicely wrapped high-level library for
multi-threading. Other thread libraries are not tested, and some are not
supported by python-for-android now, such as multiprocessing
.
Here is a little example to use threading:
import threading
def worker(arg):
print threading.currentThread().getName(), 'Starting with arg %s' % arg
t = threading.Thread(target = worker, args = (file_in, ))
t.start()
More example and tutorials can be found at https://pymotw.com/2/threading/
One important thing to notice, however, is that when you invoked any
code that calls pyjnius
, main_utils
or mi2app_utils
, you
should detach that thread in the target function. This is due to the
known issue in pyjnius
:
**jnius.detach()**
Each time you create a native thread in Python and uses Pyjnius, any call to Pyjnius methods will force attach- ment of the native thread to the current JVM. But you must detach it before leaving the thread, and Pyjnius cannot do it for you.
If you don’t, it will crash on dalvik and ART / Android
Thus, if you called any function from main_utils
or
mi2app_utils
, you should detach the thread using a wrapper function
call detach_thread
:
import threading
import main_utils
import mi2app_utils
def worker1(arg):
try:
print threading.currentThread().getName(), 'Starting with arg %s' % arg
print main_utils.get_mobile_insight_log_path()
finally:
main_utils.detach_thread()
def worker2(arg)
try:
print threading.currentThread().getName(), 'Starting with arg %s' % arg
print mi2app_utils.get_mobile_insight_log_path()
finally:
mi2app_utils.detach_thread()
t = threading.Thread(target = worker1, args = (file_in, ))
t.start()
tt = threading.Thread(target = worker2, args = (file_in, ))
tt.start()
If you used jnius
directly in your code, just call
jnius.detach()
in the corresponding place.