17

I'm trying to program a loop with a asynchronous part in it. I dont want to wait for this asynchronous part every iteration though. Is there a way to not wait for this function inside the loop to finish?

In code (example):

import time
def test():
    global a
    time.sleep(1)
    a += 1
    test()

global a
a = 10
test() 
while(1):
    print a
1
  • 1
    You don't have an async part - time.sleep is blocking. Commented Oct 9, 2017 at 14:52

5 Answers 5

33

You can put it in a thread. Instead of test()

from threading import Thread
Thread(target=test).start()
print("this will be printed immediately")
Sign up to request clarification or add additional context in comments.

Comments

11

To expand on blue_note, let's say you have a function with arguments:

def test(b):
    global a
    time.sleep(1)
    a += 1 + b

You need to pass in your args like this:

from threading import Thread
b = 1
Thread(target=test, args=(b, )).start()
print("this will be printed immediately")

Note args must be a tuple.

Comments

2

A simple way is to run test() in another thread

import threading

th = threading.Thread(target=test)
th.start()

Comments

0

You should look at a library meant for asynchronous requests, such as gevent

Examples here: http://sdiehl.github.io/gevent-tutorial/#synchronous-asynchronous-execution

import gevent

def foo():
    print('Running in foo')
    gevent.sleep(0)
    print('Explicit context switch to foo again')

def bar():
    print('Explicit context to bar')
    gevent.sleep(0)
    print('Implicit context switch back to bar')

gevent.joinall([
    gevent.spawn(foo),
    gevent.spawn(bar),
])

Comments

0

use thread. it creates a new thread in that the asynchronous function runs

https://www.tutorialspoint.com/python/python_multithreading.htm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.