首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB M0集群,python多线程

MongoDB M0集群,python多线程
EN

Stack Overflow用户
提问于 2019-10-18 02:07:03
回答 1查看 122关注 0票数 1

我有一个python应用程序,它通过web抓取并利用mongo数据库来维护记录。在执行中的某些点上,有大量的db请求传入和传出。当发生这种情况时,服务器会强制关闭我的请求,并在集群中给出以下错误:

Connections % of configured limit has gone above 80

在线程中使用pymongo的最佳实践是什么?我想像其他DMBS一样,mongodb会自动处理并发请求的调度。我是否只需要创建一个本地集群,或者将我当前的集群升级到更多连接?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-18 03:00:56

在这种情况下,典型的活动是创建输入queue.Queue并将任务放入其中,然后创建几个工作者来从队列中接收任务。如果您需要限制同时使用threading.Semaphore或threading.Lock访问资源的工作者数量,希望答案能对您有所帮助,请随时提问。

代码语言:javascript
复制
import threading as thr
from queue import Queue


def work(input_q):
    """the function take task from input_q and print or return with some code changes (if you want)"""
    while True:
        item = input_q.get()
        if item == "STOP":
            break

        # else do some work here
        print("some result")


if __name__ == "__main__":
    input_q = Queue()
    urls = [...]
    threads_number = 8 # experiment with the number of workers
    workers = [thr.Thread(target=work, args=(input_q,),) for i in range(threads_number)]
    # start workers here
    for w in workers:
        w.start

    # start delivering tasks to workers 
    for task in urls:
        input_q.put(task)

    # "poison pillow" for all workers to stop them:

    for i in range(threads_number):
        input_q.put("STOP")

    # join all workers to main thread here:

    for w in workers:
        w.join

    # show that main thread can continue

    print("Job is done.")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58438448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档