增加python中线程数的限制

时间:2015-08-12 18:02:17

标签: python multithreading

我在OS X 10.11上使用Python 2.7.10的线程模块。

我想同时运行50000个http请求:

def save_data(device):
    data = {
        'id': device['id'],
        'token': device['token'],
    }

    request = requests.post('http://localhost/save_data', data=data)
    return request.status_code == 200


def save_data_thread(device, event):
    event.wait()
    result = save_data(device)
    print 'Device id %d result: %r' % (device['id'], result)


devices = pickle.load(open('devices', 'r'))
threads = []

start_event = threading.Event()

print 'Creating threads...'

for i in range(len(devices)):
    thread = threading.Thread(target=save_data_thread, args=(devices[i], start_event))
    threads.append(thread)

print 'Starting threads...'

i = 0

for thread in threads:
    thread.start()

    i += 1
    print 'Started %d threads' % i

start_event.set()

print 'Joining threads...'

for thread in threads:
    thread.join()

print 'Working...'

但是我得到了例外:

  

thread.error:无法启动新帖子

开始第2048个帖子时。我有足够的可用内存。

是否可以增加最大线程数?

1 个答案:

答案 0 :(得分:2)

如果您需要并行执行多个请求,您可以考虑使用异步方法的框架,例如:Twisted

Python GIL一次只能运行一个Python线程。

允许的线程数通常受操作系统的限制。

编辑:

如果您想坚持使用线程方法,您可能希望以稍微不同的方式并行化您的工作。检查此post以获得类似问题的解决方案。

相关问题