In Python, we can use _threading to launch a thread easily using the _thread.start_new_thread procedure. For example,
1 | import _thread |
Unfortunately, the above threads may not finish (and be aborted) before the main script is terminated. Because we are not synchronize the threads yet. We can however, do an easy trick:
1 | while True: |
This endless loop will allow all threads to forcibly joining but the script hangs until we Ctrl+C or kill it. We can use the threading module but that requires us to write a Thread class that inherits the threading.Thread.
We can uset the threading.Event() to join the threads. For example:
1 | import _thread |
Multithreading Requests to API Server using Python’s _threading Module
Let’s launch 100 threads that sends concurrent requests to a the Load Balancer Node
https://steem.justyy.workers.dev
. And we need to store the threading.Event() in an array so that we can join all threads.
import _thread
import threading
import json
import requests
from random import randrange
def worker(evt, threadName, block):
data = {"jsonrpc":"2.0", "method":"condenser_api.get_block", "params":[block], "id":1}
r = requests.post(url="https://steem.justyy.workers.dev",json=data)
rjson = r.json()
result = rjson["result"]
print(threadName, len(result["transactions"]))
evt.set()
try:
threads = []
for i in range(100):
evt = threading.Event()
threads.append(evt)
_thread.start_new_thread( worker, (evt, "Thead-" + str(i), randrange(1, 40000000)) )
for i in threads:
i.wait()
except:
print("Error2")
As expected, it will show the following:
I have also tried other nodes, and the result seems to me that all nodes can handle multiple requests at the same time from the same origin.
Every little helps! I hope this helps!
Steem On!~
Reposted to Computing and Technology
If you like my work, please consider voting for me, thanks!
https://steemit.com/~witnesses type in justyy and click VOTE
Alternatively, you could proxy to me if you are too lazy to vote!
Also: you can vote me at the tool I made: https://steemyy.com/witness-voting/?witness=justyy
Visit me at: https://steemyy.com
This page is synchronized from the post: ‘Testing Load Balance Node’