Created Using Asynchronous programming inside a Kivy application (markdown)

timothy eichler 2016-12-17 19:07:11 +01:00
parent 69b6acaeb4
commit a2b0a64059
1 changed files with 69 additions and 0 deletions

@ -0,0 +1,69 @@
## Summary
* author: timeyyy
* kivy: >= Unknown
Using an async style of programming is much easier to reason about than using threads. If you are using [good architecture](https://www.youtube.com/watch?v=o_TH-Y78tt4) it is possible to wrap all function calls from the gui to your main application in a decorator and no longer have to worry about any blocking issues. Fanning out work to multiple processes or threads is also possible.
The async landscape for kivy is a bit lacking. The best option has been explained [here](https://github.com/kivy/kivy/issues/4799#event-897592498)
Compare with [Working with threads in kivy](https://github.com/kivy/kivy/wiki/Working-with-Python-threads-inside-a-Kivy-application). While the complexity of the thread looks manageable, Sooner or later you will be bitten with buggy non deterministic behaviour and or deadlocks.
## Usage
```python
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
import time
from async_gui.engine import Task, MultiProcessTask
from async_gui.toolkits.kivy import KivyEngine
from cpu_work import is_prime, PRIMES
engine = KivyEngine()
class MyApp(App):
def build(self):
grid = GridLayout(cols=4)
grid.add_widget(Button(text='Check Primes',
on_press=self.cpu_bound))
grid.add_widget(Button(text='Check async def',
on_press=self.async_def))
self.status = Label(text='Status')
grid.add_widget(self.status)
return grid
@engine.async
def cpu_bound(self, *_):
t = time.time()
self.status.text = "calculating..."
prime_flags = yield MultiProcessTask(
[Task(is_prime, n) for n in PRIMES]
)
print(time.time() - t)
text = '\n'.join("%s: %s" % (n, prime)
for n, prime in zip(PRIMES, prime_flags))
self.status.text = text
async def async_def(self, *_):
t = time.time()
self.status.text = "calculating..."
prime_flags = []
for n in PRIMES:
result = await is_prime(n)
prime_flags.append(result)
print(time.time() - t)
text = '\n'.join("%s: %s" % (n, prime)
for n, prime in zip(PRIMES, prime_flags))
self.status.text = text
if __name__ == '__main__':
MyApp().run()
```