Python调用Cython函数会导致核心转储



我目前正在处理一个需要Python C-API的项目
所以我在C端创建了一个类,并从它的Python端继承
其中一个C函数将来应该返回None或dict。
函数:

static PyObject* handle_data(BaseClassObject* self){
struct data *data;
static int counter= 0;
// get next data from queue
if ((data= data_queue_pop(self->data_queue))) {
// TODO: build a Python dict from data and return it
free_data(data);
counter++;
}
return Py_None;
}

在这个开发阶段,函数data_queue_pop什么都不返回,因此,这个代码总是到达return Py_None;
在Python端,我有一个流动的类:

from concurrent.futures import ThreadPoolExecutor
from threading import Thread
from time import sleep
from utils.logger import getLogger
logger = getLogger(__name__)
try:
from samplelib import BaseClass
except ImportError:
from uploadlib import BaseClass

class SomeClass(BaseClass):
def __init__(self, args):
super().__init__()
self.log = logger.getChild(self.__class__.__name__)
self.version = self.version.rstrip()  # self.version is intilaied in the C side
self.args = args
self.wait = True
self._pool = ThreadPoolExecutor(max_workers=1)
self.worker = None
def __enter__(self):
self.log.info(f"set worker")
# self.worker = Thread(target=self._handle_data)
self.worker = self._pool.submit(self._handle_data)
# self.log.info(f"worker start")
# self.worker.start()
self.log.info(f"return self")
return self
def __exit__(self, a, b, c):
self.log.info(f"exit {self.__class__.__name__}")
# self.log.info('stop thread')
self.wait = False
if self.worker:
self.log.info('wait for thread to stop')
self.log.info(self.worker.cancel())
# self.worker.join()
self.log.info('exiting...')
def _handle_data(self):
self.log.info(f"thread started")
while self.wait:
data = self.handle_data()
if data:
self.log.warning(data)
self.log.info(f"thread stopped")

def main():
args = _parse_args()
with SomeClass(args) as e:
sleep(2)
print(e.version)
# e.wait = False

if __name__ == "__main__":
main()

无论我尝试做什么,我都会得到以下错误:

Fatal Python error: deallocating None
Current thread 0x00007f8c37b17700 (most recent call first):
File "/home/ramih/SomeClass-automation/utils/some_module.py", line 50 in _handle_alert
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 56 in run
File "/usr/lib/python3.6/concurrent/futures/thread.py", line 69 in _worker
File "/usr/lib/python3.6/threading.py", line 864 in run
File "/usr/lib/python3.6/threading.py", line 916 in _bootstrap_inner
File "/usr/lib/python3.6/threading.py", line 884 in _bootstrap
Thread 0x00007f8c3aedc740 (most recent call first):
File "./test.py", line 124 in main
File "./test.py", line 130 in <module>
Aborted (core dumped)

为什么会发生这种情况
如何调试它
我能让穿线更安全吗

谢谢。

感谢@DavidW的回复,问题得到了解决,我将与大家分享,这样,如果其他人遇到这个问题,可以快速找到解决方案。在这种情况下,您有两种选择:

  • return Py_None;之前执行Py_INCREF(Py_None)
  • 调用已经包含ref增量的宏Py_RETURN_NONE

最新更新