简体   繁体   English

多处理和多线程的简单示例

[英]Simple example of Multiprocessing and multi-threading

I have the following code: 我有以下代码:

class SplunkUKAnalyser(object):

    def __init__
    def method1
    def method2
    def method2
    ...

class SplunkDEAnalyser(SplunkUKAnalyser):

    def __init__    (Over-ridden)
    def method1     (Over-ridden)
    def method2
    def method2
    ...

perform_uk_analysis():
    my_uk_analyser = SplunkUKAnalyser() 

perform_de_analysis():
    my_de_analyser = SplunkDEAnalyser()

It all works well if I just execute the below: 如果我只执行以下操作,那么一切都很好:

perform_uk_analysis()
perform_de_analysis()

How can I make it so that the two last statements are executed concurrently. 我怎样才能使最后两个语句同时执行。 (using mutliprocessing and/or multi-threading)? (使用多处理和/或多线程)?

From my test it seems that the second statement executes even though the first statement has not finished completely but I would like to incorporate true concurrency. 根据我的测试,即使第一个语句尚未完全完成,第二条语句似乎仍在执行,但我想合并真正的并发。

Any other additional advice is much appreciated. 任何其他建议,我们将不胜感激。

Many thanks in advance. 提前谢谢了。

Because of GIL (Global Interpreter Lock) you can not achieve 'true concurrency' with threading . 由于存在GIL(全局解释器锁定) ,因此无法通过threading实现“真正的并发性”。

However, using multiprocessing to concurrently run multiple tasks is easy: 但是,使用multiprocessing并发运行多个任务很容易:

import multiprocessing

process1 = multiprocessing.Process(target=perform_uk_analysis)
process2 = multiprocessing.Process(target=perform_de_analysis)
# you can optionally daemoize the process
process2.daemon = True
# run the tasks concurrently
process1.start()
process2.start()
# you can optionally wait for a process to finish
process2.join()

For tasks that run the same function with different arguments, consider using multiprocessing.Pool , an even more convenient solution. 对于使用不同参数运行相同功能的任务,请考虑使用multiprocessing.Pool ,这是一个更方便的解决方案。

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

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