Python: Executing multiple functions simultaneously

后端 未结 5 2043
借酒劲吻你
借酒劲吻你 2020-11-27 04:05

I\'m trying to run two functions simultaneously in Python. I have tried the below code which uses multiprocessing but when I execute the code, the second functi

5条回答
  •  没有蜡笔的小新
    2020-11-27 04:28

    This is a very good example by @Shashank. I just want to say that I had to add join at the end, or else the two processes were not running simultaneously:

    from multiprocessing import Process
    import sys
    
    rocket = 0
    
    def func1():
        global rocket
        print 'start func1'
        while rocket < sys.maxint:
            rocket += 1
        print 'end func1'
    
    def func2():
        global rocket
        print 'start func2'
        while rocket < sys.maxint:
            rocket += 1
        print 'end func2'
    
    if __name__=='__main__':
        p1 = Process(target = func1)
        p1.start()
        p2 = Process(target = func2)
        p2.start()
        # This is where I had to add the join() function.
        p1.join()
        p2.join()
    

    Furthermore, Check this thread out: When to call .join() on a process?

提交回复
热议问题