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.
45 lines
928 B
45 lines
928 B
import asyncio
|
|
import random
|
|
import time
|
|
|
|
gesamtwert = 0
|
|
message = ''
|
|
|
|
|
|
async def calculate_sum(lock, thread_nummer):
|
|
global gesamtwert
|
|
global message
|
|
|
|
for i in range(100 + thread_nummer):
|
|
async 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
|
|
|
|
async with lock:
|
|
gesamtwert = zwischen
|
|
|
|
message = f'Thread {thread_nummer} fertig'
|
|
print(f'Thread + {thread_nummer} abgearbeitet.')
|
|
|
|
async def main():
|
|
|
|
#async Lock erzeugen
|
|
lock = asyncio.Lock()
|
|
|
|
# drei Threads starten, um die Summe der Zahlen zu berechnen
|
|
|
|
threads = [asyncio.create_task(calculate_sum(lock, _+1)) for _ in range(3)]
|
|
|
|
#Warten auf alle Threads
|
|
await asyncio.gather(*threads)
|
|
|
|
print(f'gesamtwert={gesamtwert}')
|
|
print(f'message={message}')
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(main())
|
|
|
|
|