0

I'm providing some services through REST API that will occurs DB operation while performing a request. So i'm trying to create a class that performs queries using oracledb(cx_Oracle).

A problem arises here. when that class executes a time-consuming query, i don't want other operations to block. So I looked for a lot of snippets a snippet that executes a method asynchronously. However, blocking occurred when there was a return value in all snippets.

asynchronously method without result works perfectly such as (reference : Python Threading inside a class):

def threaded(fn):
    def wrapper(*args, **kwargs):
        Thread(target=fn, args=args, kwargs=kwargs).start()
    return wrapper

class MyClass:
    somevar = 'someval'

    @threaded
    def func_to_be_threaded(self):
        time.sleep(3)
        self.finished()

    def finished(self):
        print(datetime.datetime.now(), end=' ')


test = MyClass()
test.func_to_be_threaded()
test.func_to_be_threaded()

The result is exactly what I want.

2022-07-06 16:08:54.177499 2022-07-06 16:08:54.177499 

but asynchronously method with result makes blocking. Example from the same reference

def call_with_future(fn, future, args, kwargs):
    try:
        result = fn(*args, **kwargs)
        future.set_result(result)
    except Exception as exc:
        future.set_exception(exc)


def threaded(fn):
    def wrapper(*args, **kwargs):
        future = Future()
        Thread(target=call_with_future, args=(fn, future, args, kwargs)).start()
        return future
    return wrapper


class Test:
    @threaded
    def run_something(self):
        time.sleep(5)
        return datetime.datetime.now()


test = Test()
print(test.run_something().result(), test.run_something().result())

The result is

2022-07-06 16:08:12.159146 2022-07-06 16:08:17.167825

Is there any way to wait asynchronously for the result? i don't want to hang while get query result.

Kyon
  • 65
  • 6
  • 1
    I think the key phrase in your question is "get the result." How do you want this to happen? If the rest of your program needs the result, then you must wait for it. If you don't want to wait, you need to write a callback function. And if you have a callback function, you need some means of getting its returned value into your program's main thread of execution. That means an event-driven program, an asyncio program, the use of Futures, or possibly the use of synchronization primitives. Python provides a lot of mechanisms for this purpose. The choice is up to you. – Paul Cornelius Jul 08 '22 at 00:49
  • Thank you so much. callbacks seem to be the only answer. – Kyon Jul 11 '22 at 08:01

0 Answers0