python multiprocess fails to start

后端 未结 2 1163
甜味超标
甜味超标 2021-01-16 05:09

Here is my code for a simple multiprocessing task in python

from multiprocessing import Process

def myfunc(num):

    tmp = num * num
    print \'squared O/         


        
相关标签:
2条回答
  • 2021-01-16 05:32

    Save the code above into a .py file and then run it in a gnome-terminal with

    python myfile.py
    

    Where "myfile.py" is the filename you saved to.

    I would assume that the IDE you are using is confused somehow by Process()

    0 讨论(0)
  • 2021-01-16 05:33

    With a little thought I finally found the problem.

    This is happening because in Python, the float and int objects are not 'thread-safe', meaning the memory allocated to calculate any function's value by one thread/process can be overwritten by another and hence they show absurd values. This is called a race condition.

    To solve this problem, use deque() from the collections module or, even better, use the 'Lock' facility. deque() works with arrays but it's meant for arrays of the same kind (much like MATLAB arrays) and is thread/process safe. 'Lock' avoids race conditions.

    So the edit would be :

    def myfunc(num):
    
        lock.acquire()
    
        .......some code .....
        .......some code......
    
        lock.release()
    

    That's all.

    But one problem still persists and that is with the multiprocessing module. Even after calling 'lock', the problem mentioned in the question remains.

    0 讨论(0)
提交回复
热议问题