Einfaches Beispiel aus Ernesti, Python 3, S.590, wo 'self.zahl' initialisiert und in 'run()' auch benutzt wird:
Code: Alles auswählen
import threading
class PrimzahlThread(threading.Thread):
def __init__(self, zahl):
super().__init__()
self.Zahl = zahl
def run(self):
i = 2
while i*i <= self.Zahl:
if self.Zahl % i == 0:
print(f"{self.Zahl} ist nicht prim, "
f"da {self.Zahl} = {i} * {self.Zahl // i}")
return
i += 1
print(f"{self.Zahl} ist prim")
Code: Alles auswählen
meine_threads = []
eingabe = input("> ")
while eingabe != "e":
try:
thread = PrimzahlThread(int(eingabe))
meine_threads.append(thread)
thread.start()
except ValueError:
print("Falsche Eingabe!")
eingabe = input("> ")
for t in meine_threads:
t.join()
Ausgabe vorweg:
Code: Alles auswählen
init(): 1668288720816 ( aus init )
get(): 1668288720816 ( aus init )
main #1: aus init
run(): 2795818561968 ( aus init )
run(): 2795818544112 ( aus run )
run(): 2795818544112 ( aus run )
run(): 2795818544112 ( aus run )
get(): 1668288720816 ( aus init )
main #2: aus init
Code: Alles auswählen
import multiprocessing as mp
import time
class Threadclass(mp.Process):
def __init__(self):
super().__init__()
self.daemon = True # wenn True, dann wird thread mit main beendet
self.ressource = "aus init" # Ressource die aus beiden Klassen gefunden werden soll
print("init():", id(self.ressource), "(", self.ressource, ")")
def run(self):
while True:
time.sleep(2)
print("run():", id(self.ressource), "(", self.ressource, ")")
self.ressource = "aus run"
print("run():", id(self.ressource), "(", self.ressource, ")")
def get(self):
print("get():", id(self.ressource), "(", self.ressource, ")")
return self.ressource
Code: Alles auswählen
from threadfile import Threadclass
import time
if __name__ == "__main__":
thread1 = Threadclass() # thread erstellen
thread1.start() # thread starten
print("main #1:", thread1.get())
time.sleep(5)
print("main #2:", thread1.get())