繁体   English   中英

如何在 python 中调用 function 时进行多线程或多处理

[英]How to do multithreading or multiprocessing while calling function in python

我有示例字典如下

  • 我需要找到每个属性的计数
  • 我需要使用多线程来实现
  • total(todos) 是主要的 function。 在此还有 3 个其他函数被调用。 我需要使用多线程来实现。 现在首先它会像首先执行 userid_count(todos) 一样依次执行,然后是 title_count(todos) 和 complete_count(todos)。 由于这些 function 中的每一个都是相互独立的,因此我需要处理多线程/多处理
    todos = [{'userId': 1, 'id': 1, 'title': 'A', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'B ', 'completed': False},
     {'userId': 1, 'id': 1, 'title': 'C', 'completed': False},
     {'userId': 1, 'id': 2, 'title': 'A', 'completed': True},
     {'userId': 2, 'id': 1,'title': 'B', 'completed': False}]
    def total(todos):
        user_count = userid_count(todos)
        ###### Multithreading need to implement ##########
        title = title_count(todos)
        completed = complete_count(todos)
        search_count_all = {**user_count, **title, **completed}
        return search_count_all
    
    def userid_count(todos)
        #return userid count there are 2 user id 1, 2
        #{"userid":2}
        pass
    def title_count(todos)
        #return title count there are 3 title A, B, C
        #{"title":3}
        pass
    def complete_count(todos)
        #return completed count there are Tru and False
        #{"True": 1, "False":3}
        pass
    
    total(todos)

预期结果是[{"userid":2},{"title":3},{"True": 1, "False":3} ]

您可以使用多线程来做到这一点。

import threading, queue
user_count_result = queue.Queue()
title_count_result = queue.Queue()
complete_count_result = queue.Queue()
def total(todos):
    user_countThread = threading.Thread(target=userid_count,args=(todo,user_count_result,))
    titleThread = threading.Thread(target=title_count,args=(todo,title_count_result,))
    completedThread = threading.Thread(target=complete_count,args=(todo,complete_count_result,))

    user_countThread.start()
    titleThread.start()
    completedThread.start()

    user_countThread.join()
    titleThread.join()
    completedThread.join()


    search_count_all = {**user_count_result.get(), **title_count_result.get(), **complete_count_result.get()}
    return search_count_all

def userid_count(todos, user_count_result)
    #Your logic here
    user_count_result.put({"userid": 2})

    
def title_count(todos, title_count_result)
    #Your logic here
    title_count_result.put({"userid": 2})
    
def complete_count(todos, complete_count_result)
    #Your logic here
    complete_count_result.put({"userid": 2})
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM