基于c ++的线程模型中的Python"print"

Ale*_* VI 5 c++ python printing multithreading

我通过调用C++ DLL设计一个Python应用程序,我已经发布我的DLL和Python 3.4之间的相互作用我这里.但是现在我需要在流程中执行一些涉及基于线程的模型的过程,并且我的回调函数看起来将所有prints 放入队列中,并且仅当我的流式传输结束时,才会打印所有信息.

def callbackU(OutList, ConList, nB):
    for i in range(nB):
        out_list_item = cast(OutList[i], c_char_p).value
        print("{}\t{}".format(ConList[i], out_list_item))
    return 0
Run Code Online (Sandbox Code Playgroud)

我试图使用下一种方法,但所有这些方法看起来都以相同的方式工作:

from threading import Lock

print_lock = Lock()
def save_print(*args, **kwargs):
    with print_lock:
    print (*args, **kwargs)

def callbackU(OutList, ConList, nB):
    for i in range(nB):
        out_list_item = cast(OutList[i], c_char_p).value
        save_print(out_list_item))
    return 0
Run Code Online (Sandbox Code Playgroud)

和:

import sys
def callbackU(OutList, ConList, nB):
    for i in range(nB):
        a = cast(OutList[i], c_char_p).value
        sys.stdout.write(a)
        sys.stdout.flush()
    return 0
Run Code Online (Sandbox Code Playgroud)

我希望我的回调在调用它时打印它的消息,而不是在整个过程结束时.

Ale*_* VI 2

我可以找到问题所在,我正在使用基于线程的进程,该进程需要在结束之前无限期地停留。在 C++ 中,我习惯getchar()等待进程必须结束,然后当我按下 Enter 按钮时,进程跳转到释放部分。我还尝试sleep()在 a 中使用 0.5 秒,while直到经过一定时间来测试这是否可以帮助我,但没有。这两种方法在我的 Python 应用程序中以相同的方式工作,我在流中需要的值首先放入队列中,除非进程结束,否则会打印值。

解决方案是创建两个函数,前一个函数用于初始化基于线程的模型。最后一个函数结束该过程。通过这样做,我既不需要 agetchar()也不需要 a sleep()。这对我来说非常好!谢谢您的关注!