我正在尝试增加每秒的请求量。我目前正在运行Python2.7,每秒大约能收到1个请求。我需要多线程/多处理函数还是异步运行函数的多个实例。我不知道该怎么做。请帮忙:-)
while True:
r = requests.post(url, allow_redirects=False, data={
str(formDataNameLogin): username,
str(formDataNamePass): password,
})
print 'Sending username: %s with password %s' % (username, password)
您可以使用多线程执行多个类似的并行请求:
输出:
^{pr2}$尽管我不是多线程专家,但还是有一点解释:
1.排队
Queue模块允许您创建一个新的队列对象,该对象可以保存特定数量的项目。有以下方法可以控制队列:
根据我对多线程处理的一点经验,这对于控制仍要处理的数据非常有用。我有这样的情况,线程在做同样的事情,或者除了一个线程都退出了。这有助于我控制要处理的共享数据。在
2.锁定
Python提供的线程模块包含一个易于实现的locking mechanism,它允许您同步线程。通过调用
Lock()
方法创建一个新锁,该方法返回新锁。在对于更多的人类语言锁是线程模块提供的最基本的同步机制。在任何时候,锁可以由单个线程持有,也可以完全不由线程持有。如果一个线程试图持有另一个线程已经持有的锁,那么第一个线程的执行将被暂停,直到该锁被释放。在
锁通常用于同步对共享资源的访问。对于每个共享资源,创建一个锁对象。当您需要访问资源时,调用acquire来保持锁(如果需要,这将等待锁释放),然后调用release来释放它。在
3.线程
要使用线程模块实现新线程,必须执行以下操作:
一旦创建了新的Thread子类,就可以创建它的一个实例,然后通过调用start()来启动一个新线程,后者又调用run()方法。方法:
它真的更快吗?
使用单线程:
使用3个螺纹:
使用5个螺纹:
5个线程几乎快4倍。这些只是5个虚拟请求。想象一下更大的数据块。在
请注意:我只在Python2.7下针对Python3.x进行了测试,可能需要进行一些小的调整。在
只需使用任何异步库。我认为异步版本的请求,如grequest、txrequests、requests futures和requests线程最适合您。下面是grequests自述文件中的代码示例:
使用或学习其他提到的模块,比如请求线程,可能会稍微涉及一些,尤其是在Python2中
asyncio和{a3}可能更值得注意,但是,我想,学习一个已经熟悉的模块的版本会更容易。在
多线程是不必要的,但是您可以尝试mutithreading或者,也许更好的是多进程处理,看看哪个性能最好。在
相关问题 更多 >
编程相关推荐