0

Before you tell me to look at this link, please know I have already tried that approach and I can't understand it. Maybe I'm using it wrong, but it didn't work for me.

import threading
import asyncio
from collections import deque
import queue
f = queue.Queue()
nq = deque()
loop = asyncio.get_event_loop()
async def t():
    return 5
def func():
    f.put(t())
func()
class T(threading.Thread):
    def func(self, value):
        fut = asyncio.run_coroutine_threadsafe(value, loop)
        nq.append(fut)
        print(nq) # deque([<Future at 0x3afa0a0 state=pending>])
    def run(self):
        while True:
            try:
                x = f.get(0.2)
                print(x) # <coroutine object t at 0x03AF5068>
            except:
                continue
            self.func(x)
T().start()
while True:
    try:
        val = nq.pop()
        break
    except IndexError:
        continue
print(val) # <Future at 0x3afa0a0 state=pending>
# I'm not even bothering to call `val.result()` because I know the future doesn't have a result set.

I am not sure as to why this future never resolves. Essentially, what I am trying to do is run a coroutine in a thread and return the result in the main thread with the help of a queue/container system.

hipeople321
  • 122
  • 1
  • 9
  • For starters, you never actually *run* the event loop. The code seems inscrutable, with multiple functions named `func` and using both a queue and a deque. Could you please decide precisely what you want to achieve, e.g. "I want to be able to execute a coroutine from sync code without blocking it"? I'm pretty sure whatever you need can be done much simpler. – user4815162342 Jul 22 '20 at 06:18
  • Truthfully, this is just experimentation. I don't have a concrete reason to use this *yet*, but I might in the future. I apologize for the bad variable names, that's a bad habit of mine. Anyway, in regards to your comment: "you never actually run the event loop.", I would be appreciative if you told me how to run it in this example. Thanks for giving your insight! – hipeople321 Jul 22 '20 at 13:26
  • Please describe what you want to do and we'll show you how to do it. As it stands, all we have is some code that is unclear _and_ unfinished, without any description of what it's supposed to be doing. All we know is that you tried the approach from the other question and that it "didn't work". The question is pretty much unanswerable in its current form. – user4815162342 Jul 22 '20 at 13:52

0 Answers0