![](/img/trans.png)
[英]How to implement Multithreading/Multiprocessing in Python by merging the function
[英]How to do multithreading or multiprocessing while calling function in python
我有示例字典如下
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.