您可以使用标准Python库中的信号量对象:
python doc
或者,如果您想直接处理线程,可以使用wait([timeout])。在
没有与Python捆绑的库可以在以太网或其他网络接口上工作。你能用的最低的是插座。在
根据你的答复,我有个建议。请注意活动的\u计数。仅用于测试脚本是否只运行两个线程。在这个例子中,它们是三个,因为第一个是你的脚本,然后你有两个URL请求。在import time
import requests
import threading
# Limit the number of threads.
pool = threading.BoundedSemaphore(2)
def worker(u):
# Request passed URL.
r = requests.get(u)
print r.status_code
# Release lock for other threads.
pool.release()
# Show the number of active threads.
print threading.active_count()
def req():
# Get URLs from a text file, remove white space.
urls = [url.strip() for url in open('urllist.txt')]
for u in urls:
# Thread pool.
# Blocks other threads (more than the set limit).
pool.acquire(blocking=True)
# Create a new thread.
# Pass each URL (i.e. u parameter) to the worker function.
t = threading.Thread(target=worker, args=(u, ))
# Start the newly create thread.
t.start()
req()