我有一个python程序,它使用ctypes来调用一个dll函数,我向它传递一个指针。它应该连续地向指针写入数据,我希望我的程序循环并读取指针的内容。粗略的模板如下所示:from ctypes import *
import copy
lib = cdll.lib
pointer = c_char_p(" "*100) #however large a buffer I need
#thread this
lib.dostuff(pointer)
#end thread
while True:
data = pointer.value
print data
在我的具体例子中,dostuff()是用C编写的,打开一个文件并对其进行解码,将数据作为流运行到字符数组中。在
问题是我不能使用python中的常规线程模块,因为线程持有GIL,因为读取dll被认为是文件I/O,或者dll本身是文件I/0。因此,在dostuff()完成之前,循环不会运行。它阻塞的原因是什么(dll调用总是阻塞吗?)我该怎么办?在
编辑:
----------已解决----------------------
正如samplebias在下面指出的,ctypes释放了GIL锁。我发现程序中的阻塞问题是我正在运行一个队列:
代码看起来有点像这样
^{pr2}$
程序被阻止是因为队列.get()当队列为空时阻塞,直到有东西进入队列!当然,由于我没有单独线程dll调用,所以它在我将指针结果推送到队列之前就完成了。解决方案看起来有点像:import Queue
from threading import Thread
queue = Queue()
def runthread():
q = Thread(target=lib.dostuff, args=(pointer,))
q.start()
while True:
queue.put(pointer.value)
thread = Thread(target=runthread)
thread.start()
while True:
data = queue.get()
dostuffwithdata(data)
我希望这对某人有帮助!在