Skip to content
threads.py 1.58 KiB
Newer Older
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May  4 11:43:50 2019

Here an example of a correct way of creating a thread that executes a loop, 
which can be ended safely. 

@author: martindrech
"""

import threading
import time

def do_something():
    print('do something')

def loop_function():
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        do_something()
        time.sleep(1)

def stop_loop_thread(some_thread):
    some_thread.do_run = False
    some_thread.join()

#%%
#deine a thread where target function will be executed
some_thread = threading.Thread(
                target=loop_function
)
# start thread, wait 5 seconds, and then stop the thread
some_thread.start()
time.sleep(5)
stop_loop_thread(some_thread)

Martin Drechsler's avatar
Martin Drechsler committed
#%%########################################################################################
from PyQt5 import QtCore
def block_until_emit(signal, timeout=10000):
    """Block loop until signal emitted, or timeout (ms) elapses."""
    loop = QtCore.QEventLoop()
    signal.connect(loop.quit)

    yield

    if timeout is not None:
        QtCore.QTimer.singleShot(timeout, loop.quit)
    loop.exec_()

#%%
def loop_function(trigger_signal):
    while True:
        do_something()
        block_until_emit(trigger_signal)

class Emitter(QtCore.QObject):
    signal = QtCore.pyqtSignal()
    def __init__(self):
        super().__init__()
#%%

emitter = Emitter()
some_thread = threading.Thread(
                target=lambda :loop_function(emitter.signal)
)
# start thread, wait 5 seconds, and then stop the thread
some_thread.start()