'how to start new thread in python async function
i want to start new thread in async function,so i write the code below
def mutli_buy():
threads = []
for i in range(10):
t = threading.Thread(target=buy, args=(i))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
async def txn_handler(txn):
if txn == 1:
mutli_buy()
else:
pass
but it failed with error , so how to start new thread in python async function , i have read many articiles in google
Solution 1:[1]
Personally, I use the threading library. It works perfectly fine for all my needs.
import time
from threading import Thread
def test(s):
time.sleep(2)
print(s)
def main():
t = Thread(target=test, args=("World!",)) # always keep the , even when there is only one argument!!
t.start()
print("Hello, ")
time.sleep(3)
if __name__ == '__main__':
main()
I just ran this and it worked perfectly fine. Just a few things to keep in mind: I am unaware of how to stop a thread. What I do is I just have a variable that tells the thread whether to run or not (my threads have foever loops) and if they dont run then I just end the loop and the threaded function ends and consequentyly so does the thread.
When passing the target function, dont call it. Do 'test', not 'test()'. if you use the ladder then it will call the function test and take its return value as the target value.
Lastly, when parsing values via the args function, make sure to put a comma after the value whenthere is only one variable/value being parsed because "world" would turn into 'w, o, r, l, d', and '"world",' turns into "world".
Solution 2:[2]
maybe you can try python-worker (link)
from worker import worker
@worker
def buy(n):
...
def mutli_buy():
for i in range(10):
buy(i)
async def txn_handler(txn):
if txn == 1:
mutli_buy()
else:
pass
your buy function will be run as a thread
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KingTasaz |
| Solution 2 | danangjoyoo |
