Home > OS >  got an error while running a simple multithreading code
got an error while running a simple multithreading code

Time:02-06

I did a research but the only thing I saw was the if __name__ == '__main__' thing, which didn't help. can you help me spot the problem?

here's the code:

import multiprocessing
from multiprocessing import *
manager = Manager()
sharedVar = manager.Value()
sharedVar.value = 0


def worker():
    sharedVar.value = 1432


if __name__ == '__main__':
    process1 = multiprocessing.Process(target=worker)

    process1.start()
    process1.join()

    print(sharedVar)

and the error:

raise RuntimeError('''
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

Process finished with exit code -1

CodePudding user response:

The problem is you still initialize Manager outside of if __name__ == '__main__': block so when new process is spawn it tries to create another instance of this class and that's where error occurs. Also you have second issue there - manager.Value() requires two parameters - 'typecode' and 'value'.

Here's slightly modified working version of your code:

from multiprocessing import Manager, Process


def worker(sharedValue):
    sharedValue.value = 1432


if __name__ == '__main__':
    manager = Manager()
    sharedVar = manager.Value("i", 0)
    process1 = Process(target=worker, args=(sharedVar,))

    process1.start()
    process1.join()

    print(sharedVar)
  •  Tags:  
  • Related