Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'print' in a c++ based threading model

I am designing a Python app by calling a C++ DLL, I have posted my interaction between my DLL and Python 3.4 here. But now I need to do some process in streaming involving a threading based model and my callback function looks to put in a queue all the prints and only when my streaming has ended, all the Info is printed.

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

I have tried to use the next ways, but all of them looks to work in the same way:

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

and:

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

I would like that my callback prints its message when the it is called, not when the whole process ends.

like image 450
Alexander Leon VI Avatar asked Oct 30 '22 15:10

Alexander Leon VI


1 Answers

I can find what was the problem, I am using a thread based process that needs to stay for an indefinite time before end it. In c++ I'm using getchar() to wait until the process has to be ended, then when I pushed the enter button the process jump to the releasing part. I also tried to use sleep()s of 0.5 secs in a while until a definite time has passed to test if that could help me, but it didn't. Both methods worked in the same way in my Python application, the values that I needed to have in streaming were put in a queue first and unless the process ended that values were printed.

The solution was to make two functions, the former one for initialize the thread based model. And the last one function for ends the process. By so doing I didn't need a getchar() neither a sleep(). This works pretty good to me!, thanks for you attention!

like image 166
Alexander Leon VI Avatar answered Nov 15 '22 05:11

Alexander Leon VI