I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process if it runs too long (which i cant do with threads).
Essentially, my program is
if __name__ == '__main__':
pool = Pool(processes=1)
while ...:
source = generate() #autogenerate code
exec(source)
print meth() # just a test, prints a result, since meth was defined in source
result = pool.apply_async(meth)
try:
print result.get(timeout=3)
except:
pool.terminate()
This is the code that should work, but doesn't, instead i get
AttributeError: 'module' object has no attribute 'meth'
It seems that Pool only sees the meth method, if it is defined in the very top level. Any suggestions how to get it to run dynamically created method?
Edit: the problem is exactly the same with Process, i.e.
source = generated()
exec(source)
if __name__ == '__main__':
p = Process(target = meth)
p.start()
works, while
if __name__ == '__main__':
source = generated()
exec(source)
p = Process(target = meth)
p.start()
doesn't, and fails with an AttributeError