You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
937 B
44 lines
937 B
2 years ago
|
import threading
|
||
|
import time
|
||
|
import random
|
||
|
|
||
|
gesamtwert = 0
|
||
|
message = ''
|
||
|
lock = threading.Lock()
|
||
|
|
||
|
|
||
|
def calculate_sum(thread_nummer,lock):
|
||
|
global gesamtwert
|
||
|
global message
|
||
|
|
||
|
for i in range(100 + thread_nummer):
|
||
|
with lock:
|
||
|
zwischen = gesamtwert
|
||
|
#Zufällige Wartezeit zwischen 0,1s und 0,5s
|
||
|
wartezeit = random.randint(1,5+thread_nummer)
|
||
|
time.sleep(0.1 * wartezeit)
|
||
|
|
||
|
zwischen += 1
|
||
|
|
||
|
with lock:
|
||
|
gesamtwert = zwischen
|
||
|
|
||
|
message = f'Thread {thread_nummer} fertig'
|
||
|
print(f'Thread + {thread_nummer} abgearbeitet.')
|
||
|
|
||
|
# zwei Threads starten, um die Summe der Zahlen zu berechnen
|
||
|
gesamtwert = 0
|
||
|
t1 = threading.Thread(target=calculate_sum, args=(1,lock,))
|
||
|
t2 = threading.Thread(target=calculate_sum, args=(2,lock,))
|
||
|
t3 = threading.Thread(target=calculate_sum, args=(3,lock,))
|
||
|
t1.start()
|
||
|
t2.start()
|
||
|
t3.start()
|
||
|
t1.join()
|
||
|
t3.join()
|
||
|
t2.join()
|
||
|
|
||
|
|
||
|
print(f'gesamtwert={gesamtwert}')
|
||
|
print(f'message={message}')
|