[英]How to use multithreading.Value in dataclass?
你們中有人知道是否可以在dataclass
中使用multiprocessing.Value
字段嗎?
對於以下數據類定義,我得到TypeError: this type has no size
exception。
import multiprocessing
from dataclasses import dataclass
@dataclass
class TestResults:
count: multiprocessing.sharedctypes.Synchronized = multiprocessing.Value(int, 0)
堆棧跟蹤:
$ python example.py
Traceback (most recent call last):
File "/tmp/example.py", line 5, in <module>
class TestResults:
File "/tmp/example.py", line 6, in TestResults
count: multiprocessing.sharedctypes.Synchronized = multiprocessing.Value(int, 0)
File "/usr/lib/python3.10/multiprocessing/context.py", line 135, in Value
return Value(typecode_or_type, *args, lock=lock,
File "/usr/lib/python3.10/multiprocessing/sharedctypes.py", line 74, in Value
obj = RawValue(typecode_or_type, *args)
File "/usr/lib/python3.10/multiprocessing/sharedctypes.py", line 49, in RawValue
obj = _new_value(type_)
File "/usr/lib/python3.10/multiprocessing/sharedctypes.py", line 40, in _new_value
size = ctypes.sizeof(type_)
TypeError: this type has no size
multiprocessing.Value
需要第一個參數作為數組類型,因此對於 int,您應該傳入 2 個字節的“i”或 4 個字節整數的“l”。
由於它是可變類型,因此您需要使用field(default_factory)
來構造它。
import multiprocessing
from dataclasses import dataclass, field
import multiprocessing.sharedctypes
@dataclass
class TestResults:
count: multiprocessing.sharedctypes.Synchronized = field(default_factory=lambda: multiprocessing.Value('i', 0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.