多线程处理? [英] Multiprocessing with threading?

查看:33
本文介绍了多线程处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使我的脚本多线程时,

when I trying to make my script multi-threading,

我发现了多处理,

我想知道是否有办法使多处理与线程一起工作?

I wonder if there is a way to make multiprocessing work with threading?

  • cpu 1 -> 3 个线程(工人 A、B、C)
  • cpu 2 -> 3 个线程(worker D、E、F)
  • ...

我正在尝试自己做,但遇到了很多问题.

Im trying to do it myself but I hit so much problems.

有没有办法让这两者协同工作?

is there a way to make those two work together?

推荐答案

您可以生成多个 Processes,然后从它们内部生成 Threads.每个进程几乎可以处理标准解释器线程可以处理的任何内容,因此没有什么可以阻止您在每个进程中创建新线程甚至新进程.作为一个最小的例子:

You can generate a number of Processes, and then spawn Threads from inside them. Each Process can handle almost anything the standard interpreter thread can handle, so there's nothing stopping you from creating new Threads or even new Processes within each Process. As a minimal example:

def foo():
    print("Thread Executing!")

def bar():
    threads = []
    for _ in range(3): # each Process creates a number of new Threads
        thread = threading.Thread(target=foo) 
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()

if __name__ == "__main__": 
    processes = []
    for _ in range(3):
        p = multiprocessing.Process(target=bar) # create a new Process
        p.start()
        processes.append(p)
    for process in processes:
        process.join()

线程之间的通信可以在每个 Process 内处理,进程之间的通信可以在根解释器级别使用队列或管理器对象处理.

Communication between threads can be handled within each Process, and communication between the Processes can be handled at the root interpreter level using Queues or Manager objects.

这篇关于多线程处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆