1

I have two threads: one of them writes into a datastructre and the other monitors for changes using a while True loop.

Writer thread (Socket):

if new_mess:
  datastruct.update(..)

Reader thread:

initial_state = datastruct.get_state()
while True:
   if datastruct.get_state() !=  initial_state:
       do_sth()

The problem is that the reader blocks the writer, resulting in poor performance on the writer side. I would like to create a coroutine on the method datastruct.curr_state so it doesn't block the writer. However, I am not sure how the await condition should be structured.

Datastruct class:

class Datastruct:
  ...
  async def get_state(self, key):
    await asyncio.sleep(1)
    return self.elements.get(key)
  ...

The above method gives cedes the execution context and then the event loop moves ahead with other awaiting tasks. Clearly, this is not a good approach since the coroutine waits until the sleep useless function is executed.

At this point, you may have realized that I'm completely new to asyncio. Idk if there is an easier way of doing this non-blocking read. Any help will be greatly welcomed. Thanks!

deadlock
  • 164
  • 1
  • 14
  • Is `elements` a dictionary? There's no I/O involved in doing that lookup so it doesn't really make sense to make `get_state` awaitable. It might make more sense to add the sleep to your while loop. If you're concerned about the duration, an [Event](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event) or [Condition](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Condition) might be a better fit. – dirn Sep 29 '22 at 15:25

2 Answers2

0

Using threads to read/write concurrently on the same class instance is a bad idea due to race conditions..

Did you try using a threading.Lock with your threads to protect Datastruct access?

On the other hand, with asyncio if self.elements.get(key) is synchronous you won't get any benefits..

To fix this, you need to implement an asychronous version of get to use it like

return await self.elements.get(key)
SystemSigma_
  • 1,059
  • 4
  • 18
0

Finally I found a solution inspired by this answer: https://stackoverflow.com/a/46346184/11494333

Also, kudos for @dirn for suggesting the use of Events.

deadlock
  • 164
  • 1
  • 14