[英]multiprocessing and multithreading in python 3
I know that there is a GIL in python that forces threads to execute on only 1 core.我知道 python 中有一个 GIL 强制线程仅在 1 个核心上执行。 But I created processes by the number of processor cores, and in each process I create threads.
但是我根据处理器内核的数量创建进程,并在每个进程中创建线程。 In theory, will they be executed in parallel in each process?
理论上,它们会在每个进程中并行执行吗? And if it works, how can I synchronize everything while using Pool
如果它有效,我如何在使用 Pool 时同步所有内容
from multiprocessing import Pool
from concurrent.futures import ThreadPoolExecutor
def make_threads(data):
with ThreadPoolExecutor(len(data)) as executor:
answer=list(executor.map(some_function,data))
return answer
def main():
with Pool(processes_count) as p:
answer=list(p.map(make_threads,data))```
Use concurrent.futures instead of multiprocessing or multithreading if you can - it's a better API that allows you to conveniently switch from threads to processes, or vice-versa.如果可以,请使用 concurrent.futures 而不是多处理或多线程 - 这是一个更好的 API,可让您方便地从线程切换到进程,反之亦然。
Within a given python process, threads can do I/O bound tasks well, but CPU-bound tasks poorly.在给定的 python 进程中,线程可以很好地完成 I/O 绑定任务,但 CPU 绑定任务很差。 And if you have 20 I/O bound threads and 1 CPU-bound thread in a single process, then they all will have performance problems - the CPU-bound thread messes up the I/O bound threads.
如果你在一个进程中有 20 个 I/O 绑定线程和 1 个 CPU 绑定线程,那么它们都会有性能问题——CPU 绑定线程搞乱了 I/O 绑定线程。
Often Queues are the best way to communicate across processes and threads.通常,队列是跨进程和线程进行通信的最佳方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.