Emily
Emily

Reputation: 2331

Processer Efficient Way To Listen For Variable Change In Thread

I'm running threads that output to the console.

To know when to output to the console I'm using a listener for a variable change.

But that listener is burning a lot of processing power during the loop. Is there a more efficient way to listen for the change?

Here's the code:

def output_console_item(message, sound=None, over_ride_lock=False):
    log = StandardLogger(logger_name='output_console_item')
    # lock to serialize console output
    lock = threading.Lock()

    def print_msg(message):

        # Wait until console lock is released.
        if over_ride_lock is False:
            while True:
                if CONSOLE_CH.CONSOLE_LOCK is False:
                    break
                # time.sleep(0.10)

        # Make sure the whole print completes or threads can mix up output in one line.
        with lock:
            print(message)

    return

thread = Thread(target=print_msg, args=(message,))
thread.start()
thread.join()

if sound:
    thread = Thread(target=play_sound, args=(sound,))
    thread.start()
    thread.join()

Upvotes: 0

Views: 294

Answers (1)

kill129
kill129

Reputation: 100

you don't need another thread to print things for you,

you can create a safe print, something like

lock = threading.Lock()
def safe_print(message):
    with lock:
        print message

and use it in all your threads

or even better use python module Logging which is already threadsafe

edit:

you can change CONSOLE_LOCK to be a real lock and use it something like this

def print_msg(message):

    # Wait until console lock is released.
    if over_ride_lock is False:
        with CONSOLE_LOCK:
            pass


    with lock:
        print(message)

and instead of doing CONSOLE_LOCK = True do CONSOLE_LOCK.acquire and instead of doing CONSOLE_LOCK = False do CONSOLE_LOCK.release()

Upvotes: 1

Related Questions