InfiniteLooper
InfiniteLooper

Reputation: 394

multiproccesing and error The process has forked and you cannot use this CoreFoundation functionality safely

I'm having this error when calling my function start and using the multiprocessing module on Python 2.7.8 . I'm using a mac OS 10.9.5.

The process has forked and you cannot use this CoreFoundation functionality safely. 
You MUST exec(). Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_
COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug.

Here is the code, under the classe Lattice. My function sansfin is working well and is returning a boolean, it only take as an argument self and an integer to loop on.

    def start(self):
        if __name__ == '__main__':
            self.run = True
            p = Process(target=self.sansfin, args=(1000,))
            p.start()
            p.join()

    def stop(self):
        self.run = False

I am quite lost with this message. I don't have found anything helpful there and elsewhere. Some are suggesting a bug ...

Upvotes: 9

Views: 11108

Answers (2)

Michael Altfield
Michael Altfield

Reputation: 2787

To fix this error, you need to explicitly set the multiprocessing start method to spawn on MacOS. This can be achieved by adding the following immediately below if __name__ == '__main__'. For example:

import platform, multiprocessing
...
if __name__ == '__main__':
    if platform.system() == "Darwin":
        multiprocessing.set_start_method('spawn')

See Also:

  1. https://groups.google.com/forum/#!topic/psychopy-users/quulKzsQY-Y
  2. https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
  3. https://bugs.python.org/issue33725

Upvotes: 9

CoMartel
CoMartel

Reputation: 3591

You should write your script in 2 parts : your function/classes first, and a second part where you create the instances you need and call the functions you want.

The if __name__ == '__main__': is here to split these 2 parts. As you put it in your example, I think every process will try to launch itself, and will fork forever, leading to this error.

Here is what your code should look like:

class Lattice:
    def __init__(self):
        # init what you need

    def start(self):
        self.run = True
        p = Process(target=self.sansfin, args=(1000,))
        p.start()
        p.join()

    def stop(self):
        self.run = False

if __name__ == '__main__':
    lattice_instance=Lattice()
    lattice_instance.start()
    # wait the time you need
    lattice_instance.stop()

Let me know if this help with your issue.

You can also find a very good explanation on the main here : What does if __name__ == "__main__": do?

Upvotes: 0

Related Questions