Help on Simple Threading Example

40 views
Skip to first unread message

João Abrantes

unread,
Apr 17, 2015, 5:36:39 AM4/17/15
to kivy-...@googlegroups.com
I have some functions that take a while to run, so if they are run on the mainthread the whole interface will freeze. I want to run those functions on a separate thread and on the main thread I would the image of a spinner rotating just to show the user that we're working on his request. I tried to create a wrapper for these functions that take a lot of time to complete:


def add_spinner(func):


    def inner(self,*args,**kwargs):


        root = self.get_root_window()


        spinner = Spinner()


        root.add_widget(spinner)


        trigger = Clock.schedule_once(partial(func,self,*args,**kwargs))


        trigger()


    return inner

@add_spinner
def slow_function(dt):
   
#do some very intensive computations here


But it doesn't work the whole interface still freezes and the spinner only starts to rotate when the function is over. Thanks for the help.

João Abrantes

unread,
Apr 17, 2015, 6:41:47 AM4/17/15
to kivy-...@googlegroups.com
just tested this on an even simpler example, doing:


def func(dt):


    print 'start'


    sleep(10)


    print 'finnish'


Clock.schedule_once(func)


will freeze my entire interface. Should I use the threading python library instead? I've heard multiprocessing is not compatible with android or iOs.

João Abrantes

unread,
Apr 17, 2015, 10:14:17 AM4/17/15
to kivy-...@googlegroups.com
Already solved my own problem. Sorry for the spam. Threading is the way to go, it seems that kivy's UrlRequest already uses threading. If you want an example that solves the problem of slow functions freezing the interface here it is:


from threading import Thread



class Dispatcher(Thread):


    def __init__(self,func,on_terminate,*args,**kwargs):


        super(Dispatcher,self).__init__()


        self.func = func


        self.args = args


        self.kwargs = kwargs


        self.on_terminate = on_terminate


        self.start()


   


    def run(self):


        self.func(*self.args,**self.kwargs)


        if self.on_terminate:


            self.on_terminate()




def add_spinner(func):


    def inner(*args,**kwargs):


        root = args[0].get_root_window()


        spinner = Spinner()


        root.add_widget(spinner)


        on_terminate = lambda: root.remove_widget(spinner)


        Dispatcher(func,on_terminate,*args,**kwargs)


    return inner

class MyWidget(SomeWidget):
 
@add_spinner
     
def slow_function(self):

Reply all
Reply to author
Forward
0 new messages