在两个进程

时间:2017-01-05 09:46:35

标签: python multithreading dictionary

我想在两个进程之间共享一个线程对象的字典。我还有另一个对象的词典,目前似乎有效。

问题是当我尝试向dict添加键/值对时引发异常(key是一个整数而value是线程对象):

Exception with manager.dict()
    TypeError: can't pickle _thread.lock objects

我尝试从manager.dict()切换到manager.list(),但它也不起作用:

Exception with manager.list()
    TypeError: can't pickle _thread.lock objects

readFiles()功能正常运行。

我使用的是python 3.5.1(Anaconda)

def startAlgorithm(fNameGraph, fNameEnergyDistribution, fNameRouteTables):
    global _manager, _allTiesets, _allNodes, _stopDistribution

    _manager = Manager()
    _allTiesets = _manager.dict()
    _allNodes = _manager.dict()

    _stopDistribution = Value(c_bool, False)

    readFiles(fNameGraph, fNameEnergyDistribution, fNameRouteTables)
    initializeAlgorithm()

    procTADiC = Process(target=TADiC, args=(_stopDistribution, _allNodes))
    procTA = Process(target=TIESET_AGENT, args=(_stopDistribution, _allNodes, _allTiesets))
    procTADiC.start()
    procTA.start()

    procTADiC.join()
    procTA.join()


def initializeAlgorithm():
    global _graphNX, _routingTable, _energyDistribution, _energyMeanValue

    #Init all Nodes
    allNodeIDs = _graphNX.nodes()
    energySum = 0
    for node in allNodeIDs:
        nodeEnergyLoad = float(_energyDistribution.get(str(node)))
        nodeObj = Node(node, nodeEnergyLoad)
        _allNodes[node] = nodeObj
        energySum = energySum + nodeEnergyLoad

    #Calculate the mean value from the whole energy in the graph
    _energyMeanValue = energySum / len(allNodeIDs)

    #Init all Tieset-Threads
    for tieset in _routingTable:
        tiesetID = int(tieset['TiesetID'])
        connNodes = list(tieset['Nodes'])
        connEdges = list(tieset['Edges'])
        adjTiesets = list(tieset['AdjTiesets'])
        tiesetThread = Tieset(tiesetID, connNodes, connEdges, adjTiesets)
        _allTiesets[tiesetID] = tiesetThread        # Raise Exception!!!!!!!!!!


class Node:
    'Node-Class that hold information about a node in a tieset'

    def __init__(self, nodeID, energyLoad):
        self.nodeID = nodeID
        self.energyLoad = energyLoad
        self.tiesetFlag = False


class Tieset(threading.Thread):
    'Tieset-Class as Thread to distribute the load within the tieset'

    def __init__(self, tiesetID, connectedNodes, connectedEdges, adjTiesets):
        threading.Thread.__init__(self)
        self.tiesetID = tiesetID
        self.connectedNodes = connectedNodes
        self.connectedEdges = connectedEdges
        self.adjTiesets = adjTiesets
        self.leaderNodeID = min(int(n) for n in connectedNodes)
        self.measureCnt = 0


    def run(self):
        print('start Thread')

1 个答案:

答案 0 :(得分:0)

我可以说你不能在进程之间共享线程,如果你想在不同的进程中启动它们,你可以共享这些线程的参数,或者你可以共享一些结果。你看到的问题是由进程创建的本质引起的,在python中所有的参数都会在你当前的进程中被序列化,然后传递给一个新的,然后python会在那里反序列化它们来运行“目标”。显然,线程对象不可序列化(您可以检查这个有趣的线程以了解序列化问题debugging pickle)。