7 # |
7 # |
8 # See COPYING.Runtime file for copyrights details. |
8 # See COPYING.Runtime file for copyrights details. |
9 |
9 |
10 from __future__ import absolute_import |
10 from __future__ import absolute_import |
11 import sys |
11 import sys |
12 from threading import Lock, Condition |
12 from threading import Lock, Condition, Thread |
|
13 |
13 import six |
14 import six |
14 from six.moves import _thread |
15 from six.moves import _thread |
15 |
16 |
16 |
17 |
17 class job(object): |
18 class job(object): |
84 else: |
85 else: |
85 break |
86 break |
86 |
87 |
87 self.mutex.release() |
88 self.mutex.release() |
88 |
89 |
|
90 def interleave(self, waker, *args, **kwargs): |
|
91 """ |
|
92 as for twisted reactor's interleave, it passes all jobs to waker func |
|
93 additionaly, it creates a new thread to wait for new job. |
|
94 """ |
|
95 self.feed = Condition(self.mutex) |
|
96 self._threadID = _thread.get_ident() |
|
97 |
|
98 def wakerfeedingloop(): |
|
99 self.mutex.acquire() |
|
100 self.enabled = True |
|
101 if args or kwargs: |
|
102 def first_job_todo(): |
|
103 _job = job(*args, **kwargs) |
|
104 _job.do() |
|
105 if not _job.success: |
|
106 self.reraise(_job) |
|
107 self.mutex.acquire() |
|
108 self.feed.notify() |
|
109 self.mutex.release() |
|
110 waker(first_job_todo) |
|
111 self.feed.wait() |
|
112 |
|
113 while not self._finish: |
|
114 self.todo.wait() |
|
115 def job_todo(): |
|
116 self.mutex.acquire() |
|
117 if self.job is not None: |
|
118 self.job.do() |
|
119 self.feed.notify() |
|
120 self.done.notify() |
|
121 self.mutex.release() |
|
122 waker(job_todo) |
|
123 self.feed.wait() |
|
124 |
|
125 self.mutex.release() |
|
126 self.own_thread = Thread(target = wakerfeedingloop).start() |
|
127 |
|
128 def stop(): |
|
129 """ |
|
130 !interleave |
|
131 """ |
|
132 self.mutex.acquire() |
|
133 self._finish = True |
|
134 self.enabled = False |
|
135 self.job = None |
|
136 self.todo.notify() |
|
137 self.done.notify() |
|
138 self.mutex.release() |
|
139 self.own_thread.join() |
|
140 |
89 def call(self, *args, **kwargs): |
141 def call(self, *args, **kwargs): |
90 """ |
142 """ |
91 creates a job, execute it in worker thread, and deliver result. |
143 creates a job, execute it in worker thread, and deliver result. |
92 if job execution raise exception, re-raise same exception |
144 if job execution raise exception, re-raise same exception |
93 meant to be called by non-worker threads, but this is accepted. |
145 meant to be called by non-worker threads, but this is accepted. |