Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not wait for function to finish python

Tags:

python

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
like image 589
Lucas Mähn Avatar asked Oct 09 '17 14:10

Lucas Mähn


3 Answers

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

from threading import Thread
Thread(target=test).start()
print("this will be printed immediately")
like image 130
blue_note Avatar answered Oct 30 '22 00:10

blue_note


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.

like image 32
Marc LaBelle Avatar answered Oct 29 '22 22:10

Marc LaBelle


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

import threading

th = threading.Thread(target=test)
th.start()
like image 2
Jacky1205 Avatar answered Oct 30 '22 00:10

Jacky1205