Teile 10 bis 12.
This commit is contained in:
37
teil12/race_condition.py
Normal file
37
teil12/race_condition.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import threading
|
||||
import time
|
||||
import random
|
||||
|
||||
gesamtwert = 0
|
||||
message = ''
|
||||
|
||||
def calculate_sum(thread_nummer):
|
||||
global gesamtwert
|
||||
global message
|
||||
|
||||
for i in range(100 + thread_nummer):
|
||||
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
|
||||
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,))
|
||||
t2 = threading.Thread(target=calculate_sum, args=(2,))
|
||||
t3 = threading.Thread(target=calculate_sum, args=(3,))
|
||||
t1.start()
|
||||
t2.start()
|
||||
t3.start()
|
||||
t1.join()
|
||||
t3.join()
|
||||
t2.join()
|
||||
|
||||
|
||||
print(f'gesamtwert={gesamtwert}')
|
||||
print(f'message={message}')
|
Reference in New Issue
Block a user