The initialize function is called thus:
def worker(...):
...
if initializer is not None:
initializer(*args)
so there is no return value saved anywhere. You might think this dooms you, but no! Each worker is in a separate process. Thus, you can use an ordinary global
variable.
This is not exactly pretty, but it works:
cursor = None
def set_global_cursor(...):
global cursor
cursor = ...
Now you can just use cursor
in your process_data
function. The cursor
variable inside each separate process is separate from all the other processes, so they do not step on each other.
(I have no idea whether psycopg2
has a different way to deal with this that does not involve using multiprocessing
in the first place; this is meant as a general answer to a general problem with the multiprocessing
module.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…