Updated Finnish translation
[rhythmbox.git] / plugins / rb / Coroutine.py
bloba2b0e4a625a42f6660239997579591a5059486e4
1 # -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*-
3 # Copyright (C) 2006 - Ed Catmur <ed@catmur.co.uk>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2, or (at your option)
8 # any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 class Coroutine:
20 """A simple message-passing coroutine implementation.
21 Not thread- or signal-safe.
22 Usage:
23 def my_iter (plexer, args):
24 some_async_task (..., callback=plexer.send (tokens))
25 yield None
26 tokens, (data, ) = plexer.receive ()
27 ...
28 Coroutine (my_iter, args).begin ()
29 """
30 def __init__ (self, iter, *args):
31 self._continuation = iter (self, *args)
32 self._executing = False
33 def _resume (self):
34 if not self._executing:
35 self._executing = True
36 try:
37 try:
38 self._continuation.next ()
39 while self._data:
40 self._continuation.next ()
41 except StopIteration:
42 pass
43 finally:
44 self._executing = False
45 def clear (self):
46 self._data = []
47 def begin (self):
48 self.clear ()
49 self._resume ()
50 def send (self, *tokens):
51 def callback (*args):
52 self._data.append ((tokens, args))
53 self._resume ()
54 return callback
55 def receive (self):
56 return self._data.pop (0)