xasyncio 0.2.2__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xasyncio might be problematic. Click here for more details.

xasyncio/__init__.py CHANGED
@@ -1,4 +1,6 @@
1
1
  import asyncio
2
+ import dataclasses
3
+ import logging
2
4
  import threading
3
5
  import traceback
4
6
 
@@ -9,36 +11,48 @@ class ThreadingError(Exception):
9
11
  pass
10
12
 
11
13
 
12
- class AsyncThread(threading.Thread):
13
- def __init__(self, name):
14
- super().__init__()
15
- self.name = name
16
- self.events = {}
17
- self.events_out_thread = {}
18
- self.loop: asyncio.BaseEventLoop | None = None
19
- self.stopped = True
20
- self.start()
21
- self.create_out_thread_event('loop_started')
22
- self.wait_out_thread_event('loop_started')
23
-
24
- def _stop(self):
25
- """this function must be called with the thread"""
14
+ @dataclasses.dataclass
15
+ class AsyncThreadBase:
16
+ # def call_async(self, func, *args):
17
+ # raise NotImplementedError
18
+ #
19
+ # def call_sync(self, func, *args):
20
+ # raise NotImplementedError
21
+ #
22
+ # def sync_coroutine(self, coro, timeout=None):
23
+ # raise NotImplementedError
24
+ #
25
+ # def ensure_coroutine(self, coro):
26
+ # raise NotImplementedError
27
+ #
28
+ # async def await_coroutine(self, coro):
29
+ # raise NotImplementedError
30
+ #
31
+ # def stop(self):
32
+ # raise NotImplementedError
33
+ name: str = ''
34
+ loop: asyncio.AbstractEventLoop | None = None
35
+ events: dict = dataclasses.field(default_factory=dict)
36
+ events_out_thread: dict = dataclasses.field(default_factory=dict)
37
+
38
+ def _stop_self(self):
39
+ """this function must be called with this thread"""
26
40
  if self.stopped:
27
41
  return
28
42
  self.loop.stop()
29
43
  self.stopped = True
30
44
 
31
- def stop(self):
45
+ async def stop(self):
32
46
  """thread safe stop function"""
47
+ # Called in other thread
48
+
33
49
  # thread = threading.current_thread()
34
50
  # if thread == self.thread:
35
51
  # print('calling from the loop thread')
36
52
  # else:
37
53
  # print('calling from another loop')
38
54
  print(f'Threaded loop {self.name} stopping')
39
- self.call_sync(self._stop)
40
- # self.thread.join(10)
41
- self.join(10)
55
+ await self.call_sync(self._stop_self)
42
56
 
43
57
  def _mark_running(self, running=True):
44
58
  # if running:
@@ -47,25 +61,6 @@ class AsyncThread(threading.Thread):
47
61
  # print('mark stopped')
48
62
  self.stopped = not running
49
63
 
50
- def run(self):
51
- self.loop = asyncio.new_event_loop()
52
- # Need to call this in the loop, mainly because need to make sure the loop is running
53
- # debugging version
54
- # self.loop.call_soon_threadsafe(
55
- # lambda: (
56
- # print('notifying loop started'),
57
- # self._mark_running(),
58
- # print(self.stopped),
59
- # self.notify_out_thread_event('loop_started')))
60
- self.loop.call_soon_threadsafe(
61
- lambda: (
62
- self._mark_running(), self.notify_out_thread_event('loop_started')
63
- )
64
- )
65
-
66
- self.loop.run_forever()
67
- print(f'Loop ({self.name}) finished')
68
-
69
64
  def create_out_thread_event(self, name):
70
65
  self.events_out_thread[name] = threading.Event()
71
66
 
@@ -85,8 +80,44 @@ class AsyncThread(threading.Thread):
85
80
  def wait(self, event_name):
86
81
  self.events[event_name].wait()
87
82
 
88
- def call_sync(self, func, *args):
89
- blocking_call_w_loop(self.loop, func, *args)
83
+ # def call_blocking(self, func, *args):
84
+ # def call_sync(self, func, *args):
85
+ # # other thread will be blocked and could result in deadlocks
86
+ # pass
87
+
88
+ async def call_sync(self, func, *args):
89
+ # Called in other thread
90
+ # blocking_call_w_loop(self.loop, func, *args)
91
+ finish_event = asyncio.Event()
92
+ caller_loop = asyncio.get_event_loop()
93
+
94
+ def _set_finish_event():
95
+ caller_loop.call_soon_threadsafe(lambda: finish_event.set())
96
+
97
+ def _helper():
98
+ # in self thread
99
+ try:
100
+ func(*args)
101
+ _set_finish_event()
102
+ except Exception as e:
103
+ nonlocal exception
104
+ traceback.print_exc()
105
+ exception = e
106
+ _set_finish_event()
107
+
108
+ exception = None
109
+
110
+ def _ex_handler(e):
111
+ nonlocal exception
112
+ exception = e
113
+ raise exception
114
+
115
+ self.loop.set_exception_handler(_ex_handler)
116
+
117
+ self.loop.call_soon_threadsafe(_helper)
118
+ await finish_event.wait()
119
+ if exception:
120
+ raise exception
90
121
 
91
122
  def call_async(self, func, *args):
92
123
  self.loop.call_soon_threadsafe(func, *args)
@@ -95,117 +126,104 @@ class AsyncThread(threading.Thread):
95
126
  # if threading.current_thread() != self.thread:
96
127
  # raise ThreadingError('Invalid thread: this function must be called in the loop thread')
97
128
 
98
- def await_coroutine(self, coro, timeout=None):
129
+ def sync_coroutine(self, coro, timeout=None):
99
130
  return asyncio.run_coroutine_threadsafe(coro, self.loop).result(timeout)
100
131
 
101
- # finish_event = threading.Event()
102
- #
103
- # async def _helper():
104
- # try:
105
- # await coro
106
- # except Exception as e:
107
- # traceback.print_exc()
108
- #
109
- # finish_event.set()
110
- #
111
- # self.loop.call_soon_threadsafe(self.loop.create_task, _helper())
112
- # finish_event.wait()
113
-
114
-
115
- class AsyncedThread:
116
- def __init__(self, name, thread):
117
- self.thread = thread
118
- self.loop = asyncio.get_event_loop()
119
- assert self.loop.is_running() # we require the loop already running
120
- self.name = name
121
- self.events = {}
122
- self.events_out_thread = {}
123
- self.stopped = True
132
+ def ensure_coroutine(self, coro):
133
+ return asyncio.run_coroutine_threadsafe(coro, self.loop)
124
134
 
125
- def _stop(self):
126
- """this function must be called with the thread"""
127
- if self.stopped:
128
- return
129
- self.loop.stop()
130
- self.stopped = True
135
+ async def run_coroutine(self, coro):
136
+ return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(coro, self.loop))
131
137
 
132
- def stop(self):
133
- """thread safe stop function"""
134
- # thread = threading.current_thread()
135
- # if thread == self.thread:
136
- # print('calling from the loop thread')
137
- # else:
138
- # print('calling from another loop')
139
- print(f'Threaded loop {self.name} stopping')
140
- self.call_sync(self._stop)
141
- # self.thread.join(10)
142
- self.join(10)
138
+ def blocking_call_w_loop(self, loop, func, *args):
139
+ pass
143
140
 
144
- def _mark_running(self, running=True):
145
- # if running:
146
- # print('mark running')
147
- # else:
148
- # print('mark stopped')
149
- self.stopped = not running
141
+ # def sync_coroutine_deadlock(self, coro, timeout=None):
142
+ # finish_event = threading.Event()
143
+ #
144
+ # async def _helper():
145
+ # try:
146
+ # await coro
147
+ # except Exception as e:
148
+ # traceback.print_exc()
149
+ #
150
+ # finish_event.set()
151
+ #
152
+ # self.loop.call_soon_threadsafe(self.loop.create_task, _helper())
153
+ # finish_event.wait()
150
154
 
151
- def create_out_thread_event(self, name):
152
- self.events_out_thread[name] = threading.Event()
153
155
 
154
- def wait_out_thread_event(self, name):
155
- self.events_out_thread[name].wait()
156
-
157
- def notify_out_thread_event(self, name):
158
- # print('notify event', name)
159
- self.events_out_thread[name].set()
156
+ class AsyncThread(threading.Thread, AsyncThreadBase):
157
+ def __init__(self, name):
158
+ # super(AsyncThread, self).__init__()
159
+ threading.Thread.__init__(self)
160
+ AsyncThreadBase.__init__(self)
161
+ self.name = name
162
+ self.events = {}
163
+ self.events_out_thread = {}
164
+ self.loop: asyncio.BaseEventLoop | None = None
165
+ self.stopped = True
166
+ self.create_out_thread_event('loop_started')
167
+ self.start()
168
+ # self.wait_out_thread_event('loop_started')
169
+ logging.debug('AsyncThread init finished and running')
160
170
 
161
- def create_event(self, name):
162
- self.events[name] = threading.Event()
171
+ def __repr__(self):
172
+ return f'<AsyncThread {self.name}>'
163
173
 
164
- def notify(self, event_name):
165
- self.events[event_name].set()
174
+ async def stop(self):
175
+ # Called in other thread
176
+ await super().stop()
177
+ res = self.join(1)
178
+ print(res)
166
179
 
167
- def wait(self, event_name):
168
- self.events[event_name].wait()
180
+ def run(self):
181
+ self.loop = asyncio.new_event_loop()
182
+ asyncio.set_event_loop(self.loop)
169
183
 
170
- def call_sync(self, func, *args):
171
- blocking_call_w_loop(self.loop, func, *args)
184
+ # Need to call this in the loop, mainly because need to make sure the loop is running
185
+ # debugging version
186
+ # self.loop.call_soon_threadsafe(
187
+ # lambda: (
188
+ # print('notifying loop started'),
189
+ # self._mark_running(),
190
+ # print(self.stopped),
191
+ # self.notify_out_thread_event('loop_started')))
172
192
 
173
- def call_async(self, func, *args):
174
- self.loop.call_soon_threadsafe(func, *args)
193
+ # self.loop.call_soon_threadsafe(
194
+ # self.loop.call_soon(
195
+ # lambda: (
196
+ # self._mark_running(), self.notify_out_thread_event('loop_started')
197
+ # )
198
+ # )
175
199
 
176
- # def _sync_coro(self, coro):
177
- # if threading.current_thread() != self.thread:
178
- # raise ThreadingError('Invalid thread: this function must be called in the loop thread')
200
+ async def _notify_running():
201
+ logging.debug('notify running')
202
+ self._mark_running()
203
+ self.notify_out_thread_event('loop_started')
179
204
 
180
- def await_coroutine(self, coro, timeout=None):
181
- return asyncio.run_coroutine_threadsafe(coro, self.loop).result(timeout)
205
+ asyncio.ensure_future(_notify_running())
182
206
 
183
- # finish_event = threading.Event()
184
- #
185
- # async def _helper():
186
- # try:
187
- # await coro
188
- # except Exception as e:
189
- # traceback.print_exc()
190
- #
191
- # finish_event.set()
192
- #
193
- # self.loop.call_soon_threadsafe(self.loop.create_task, _helper())
194
- # finish_event.wait()
207
+ logging.info('running loop')
208
+ self.loop.run_forever()
209
+ print(f'Loop ({self.name}) finished')
195
210
 
211
+ def __hash__(self):
212
+ return 0
196
213
 
197
- def blocking_call_w_loop(loop, func, *args):
198
- finish_event = threading.Event()
214
+ def __eq__(self, other):
215
+ return self is other
199
216
 
200
- def _helper():
201
- try:
202
- func(*args)
203
- finish_event.set()
204
- except Exception:
205
- traceback.print_exc()
206
217
 
207
- loop.call_soon_threadsafe(_helper)
208
- finish_event.wait()
218
+ class AsyncedThread(AsyncThreadBase):
219
+ def __init__(self, name, thread):
220
+ self.thread = thread
221
+ self.loop = asyncio.get_event_loop()
222
+ assert self.loop.is_running() # we require the loop already running
223
+ self.name = name
224
+ self.events = {}
225
+ self.events_out_thread = {}
226
+ self.stopped = True
209
227
 
210
228
 
211
229
  class ThreadSafeEvent(asyncio.Event):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: xasyncio
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: A package to simiplify multithreaded asyncio event loops
5
5
  Project-URL: Homepage, https://github.com/shawn-peng/xasyncio
6
6
  Project-URL: Bug Tracker, https://github.com/shawn-peng/xasyncio/issues
@@ -0,0 +1,5 @@
1
+ xasyncio/__init__.py,sha256=5HCq6bK0hn-fdOyrTZKty-S0fc2TC05prJifDiDZI5M,7197
2
+ xasyncio-0.2.3.dist-info/METADATA,sha256=a2gRi9YWbjkO-9RQeMuhFGbB4vzCM4npjcOfD39tPq8,488
3
+ xasyncio-0.2.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
+ xasyncio-0.2.3.dist-info/licenses/LICENSE,sha256=fHWKRzBMuHQa8EYpadXv8pSmA8XnR8FlirkvLoayV1I,1066
5
+ xasyncio-0.2.3.dist-info/RECORD,,
@@ -1,5 +0,0 @@
1
- xasyncio/__init__.py,sha256=8_wK431-8KTNTQXMiSahopLFqfgoD-tRByiTh_W3tDQ,6672
2
- xasyncio-0.2.2.dist-info/METADATA,sha256=0QCfV_eS4CKgwQ0Uc8sk4XUctmSR8FXpBilBx_l8sAU,488
3
- xasyncio-0.2.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
- xasyncio-0.2.2.dist-info/licenses/LICENSE,sha256=fHWKRzBMuHQa8EYpadXv8pSmA8XnR8FlirkvLoayV1I,1066
5
- xasyncio-0.2.2.dist-info/RECORD,,