-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy paththreads.py
More file actions
executable file
·49 lines (37 loc) · 1.17 KB
/
threads.py
File metadata and controls
executable file
·49 lines (37 loc) · 1.17 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python3
from threading import Thread
from time import sleep
import string
from sys import argv
"""
Man kann einen Thread erstellen, indem man threading.Thread importiert
und eine neue Klasse erstellt, die davon erbt und run überschreibt.
Man kann diesen Thread dann starten, indem man eine Instanz dieser Klasse anlegt
und start() darauf aufruft.
"""
class PrintThread(Thread):
def __init__(self, string: str, wait: float = 0.1) -> None:
Thread.__init__(self)
self.string = string
self.wait = wait
self.daemon = True # Soll dieser Thread beendet werden beim Programmende des Haupt-Threads?
def run(self) -> None:
while True:
print(self.string, end="", flush=True)
sleep(self.wait)
"""
Alternativ kann man auch einfach eine bestimmte Methode
in einem neuen Thread ausführen ohne eine neue Klasse zu schreiben:
def fun() -> None:
pass
Thread(target=fun).start()
"""
if len(argv) > 1:
count = int(argv[1])
else:
count = 2
for letter in string.ascii_uppercase[0:count]:
PrintThread(letter).start()
while True:
sleep(100)
# siehe auch: https://docs.python.org/3.6/library/threading.html