Created
December 5, 2020 06:06
-
-
Save chiefastro/1d95603164195316ee84d45b978b3b42 to your computer and use it in GitHub Desktop.
Fix errors thrown by singleton during multiprocessing in python by passing as argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from joblib import Parallel, delayed | |
class OnlyOne: | |
"""Singleton Class, inspired by | |
https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Singleton.html""" | |
class __OnlyOne: | |
def __init__(self, arg): | |
if arg is None: | |
raise ValueError("Pretend empty instantiation breaks code") | |
self.val = arg | |
def __str__(self): | |
return repr(self) + self.val | |
instance = None | |
def __init__(self, arg=None): | |
if not self.instance: | |
self.instance = self.__OnlyOne(arg) | |
else: | |
self.instance.val = arg | |
def __getattr__(self, name): | |
return getattr(self.instance, name) | |
def worker(num, one): | |
"""Single worker function to run in parallel. | |
""" | |
time.sleep(0.1) | |
one.val += num | |
return one.val | |
# Instantiate singleton | |
one = OnlyOne(0) | |
print(one.val) | |
# Run in parallel succeeds when one is passed | |
# as arg to worker | |
res = Parallel(n_jobs=-1, verbose=10)( | |
delayed(worker)(i, one) for i in range(10) | |
) | |
print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment