Python Forum

Full Version: Multiprocessing Can't pickle local object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I finally decided to experiment on the multiprocessing module, however I run straight into a ditch where am currently hitting my head against it's walls. I desperately need some help to get out of this, here is an example of my code structure:-
import time 
import multiprocessing

    

def vcf():
        
        d='578'      
        d1='556'       
        e='678'
        e1='64498'
        
        def abc(d,e):
                
                print(d)
                print(e)
          
        def cab(d1,e1):
        
                print(d1)
                print(e)

            
        p1 = multiprocessing.Process(target=abc,args=(d,e,))
        p2 = multiprocessing.Process(target=cab,args=(d1,e1,))
        if __name__ == "__main__":
                
                p1.start()
                p2.start()
                
                p1.join()  
                p2.join()   

vcf()

finish = time.perf_counter()
print("Finished running after seconds : ",finish)


How do I make it to run while maintaining this structure, that is without moving def abc and def cab to the Top Level Function
Incase anyone else faces the same error with the same code structure, adding global keyword word to the child function before you define it eliminates the error. I have no idea why or how it works, but it works...

import time 
import multiprocessing
 
     
 
def vcf():
        global abc
        global cab

        d='578'      
        d1='556'       
        e='678'
        e1='64498'
         
        def abc(d,e):
                 
                print(d)
                print(e)
           
        def cab(d1,e1):
         
                print(d1)
                print(e)
 
             
        p1 = multiprocessing.Process(target=abc,args=(d,e,))
        p2 = multiprocessing.Process(target=cab,args=(d1,e1,))
        if __name__ == "__main__":
                 
                p1.start()
                p2.start()
                 
                p1.join()  
                p2.join()   
 
vcf()
 
finish = time.perf_counter()
print("Finished running after seconds : ",finish