gpt4 book ai didi

python - 如何从 Cython 中的另一个线程设置 future\add 到队列的结果?

转载 作者:行者123 更新时间:2023-11-28 05:32:11 29 4
gpt4 key购买 nike

我有适用于多线程的 C++ dll。所以我用 Cython 包装了这个库并创建了特殊的接收器回调函数,它必须向 asyncio.Queue 添加一些结果。

cdef void __cdecl NewMessage(char* message) nogil:

我把它标记为 nog​​il,这个回调从另一个线程调用。在这个回调中我只使用:

with gil:
print("hello") # instead adding to Queue. print("hello") is more simple operation to demostrate problem

这里陷入了僵局。如何解决?

C++ 回调声明( header ):

typedef void (*receiver_t)(char*);
void SetReceiver(receiver_t new_rec);

cpp:

static receiver_t receiver = nullptr;

void SetReceiver(receiver_t new_rec)
{
printf("setted%i\n", (int)new_rec);
a = 123;
if (new_rec != nullptr)
receiver = new_rec;
}

赛通代码:

cdef extern from "TeamSpeak3.h":
ctypedef void (*receiver_t) (char*) nogil
cdef void __cdecl SetReceiver(receiver_t new_rec) nogil

cdef void __cdecl NewMessage(char* message) nogil:
with gil:
print("hello")

SetReceiver(NewMessage)

完整代码:.h http://pastebin.com/ZTCjc6NA

.cpp http://pastebin.com/MeygA8im

.pyx http://pastebin.com/k4X9c54P

.py http://pastebin.com/1YV7tMiF

最佳答案

这是一个猜测,但您可能有一个正在运行的 Cython/C/C++ 循环,它持有 GIL 并且从不释放它。然后强制回调永远等待它。

在普通的 Python 代码中,如果另一个线程正在等待 GIL,每隔几条指令就会释放一次 GIL。在 Cython 中,这不会自动发生。确保它确实经常发生的一种方法是在你的循环中:

while True:
# ... do stuff
with nogil:
pass

这确保每个循环释放一次 GIL。

不幸的是,我不清楚你的主循环在哪里。我想知道它是否在您的 PyTeamSpeak3 类中的 connect 中,并且可能将连接的定义更改为:

def connect(self):
with nogil:
self.thisptr.Connect()

可能有帮助?

关于python - 如何从 Cython 中的另一个线程设置 future\add 到队列的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39202891/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com