Newer
Older
Martin Drechsler
committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/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
committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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()