Python多处理阵列初始化

时间:2014-12-18 11:43:48

标签: python process python-multiprocessing

我正在尝试使用Process Arrays来跨多个进程使用Array结构,但似乎无法初始化the example

from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double,c_char_p

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

class Call(Structure):
    _fields_ = [('participantId',c_char_p)]

def modify(n,s):
    n.value **= 2
    #x.value **= 2
    s.value = s.value.upper()
    #for a in A:
    #    a.x **= 2
    #    a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
   #x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', 'hello world', lock=lock)
    A = Array(Call,['ebtirgnm-sqr7-h2fd-wa80-baoctu684qma'], lock=lock)
   #A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n,s))
    p.start()
    p.join()

    print n.value
  #  print x.value
    print s.value

在此行中使用Call Object初始化我的数组时出错:

A = Array(Call,['ebtirgnm-sqr7-h2fd-wa80-baoctu684qma',], lock=lock)


/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/gogasca/Documents/OpenSource/Development/Python/tpsEmulator/tpsEmulator/tools/Array.py
Traceback (most recent call last):
  File "/Users/gogasca/Documents/OpenSource/Development/Python/tpsEmulator/tpsEmulator/tools/Array.py", line 25, in <module>
    A = Array(Call,['1'], lock=lock)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/sharedctypes.py", line 115, in Array
    obj = RawArray(typecode_or_type, size_or_initializer)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/sharedctypes.py", line 89, in RawArray
    result.__init__(*size_or_initializer)
TypeError: expected Call instance, got str

我试过了:

  call1 = Call(["1"])
  ['1',]
  [('1')]
  [0]

没有运气

1 个答案:

答案 0 :(得分:2)

这里有一个错误:

A = Array(Call,['ebtirgnm-sqr7-h2fd-wa80-baoctu684qma'], lock=lock)

Python将字符串解释为对象,而不是参数。 它应该是:

A = Array(Call,[('ebtirgnm-sqr7-h2fd-wa80-baoctu684qma',)], lock=lock)

然后python会将其解释为参数。 示例中出现相同的错误:

call1 = Call(["1"])
['1',]
[('1')]
[0]

让我们试着看看python对最后一个逗号的看法:

>>> print [('1')]
['1']
>>> print [('1',)]
[('1',)]