ArcGIS 10.1 – Resolving Python AddIn Multiprocessing Crashes in ArcMap

arcgis-10.1arcgis-desktoparcpyparallel processingpython-addin

I would like to run a multiprocessing task from a python add-in tool. My issue is that the process keeps failing. Basically crashes ArcMap.

Here is my basic code:

def function(startOID, endOID, fc):

    wrksp = r"c:\temp\mp_addintest\data\test_%s.txt" % (int(startOID) + int(endOID))
    # real logic removed to dumb it down
    with open(wrksp, 'w') as writer:
        writer.write("%s to %s from %s \n" % (startOID, endOID, fc))
    return wrksp
class btnMP(object):
    """Implementation for src_addin.MPButton (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        pool = None
        try:
            pythonExe = os.path.join(sys.exec_prefix, 'python.exe')
            multiprocessing.set_executable(pythonExe)
            pool = multiprocessing.Pool(4)
            results = []
            for i in xrange(4):
                results.append(pool.apply_async(function, [str(1),
                                      str(i),
                                      str("test")]))
            pool.close()
            pool.join()
            for result in results:
                print result.get()
        except:
            del pool
            print 'error'

If I run the code outside of ArcMap or from a toolbox, it works without a problem, but when I put the logic inside a button, it causes arcmap to crash.

My guess is that ArcMap is running in process for all python add-ins. Is there a work around for this issue?

I've tried adding in the freeze_support() to the code as well, but that did nothing as well.

Best Answer

Parallel processing is easier 'shown than done.' In the case of stuffing this all into a button, I'm guessing two issues:

  1. Multiple threads block the ArcMap UI thread, or
  2. ArcMap puts its own schema lock on the data source and doesn't permit the python process access to the data.

Hmm looking further issue has been documented here in an ArcGIS Resources page. Schema lock looks like the culprit.

Related Question